Android Code for design fit to all mobiles

by MariGanesh 2014-07-11 12:38:01

Android Code for design fit to all mobiles

                   This code can be used to your android design fit to all mobile screen.Just pass your main layout id and content layout id in mention function
              Just copy the following code and pass your main layout id and content layout id in the following function.
    scaleContents(findViewById(, findViewById(;

public void onWindowFocusChanged(boolean hasFocus) {
		if (!scalingComplete) // only do this once
	        scaleContents(findViewById(, findViewById(;
	        scalingComplete = true;
	private void scaleContents(View rootView, View container)
	float xScale = (float)container.getWidth() / rootView.getWidth();
	float yScale = (float)container.getHeight() / rootView.getHeight();
	float scale = Math.min(xScale, yScale);
	// Scale our contents
	scaleViewAndChildren(rootView, scale);
	// Scale the given view, its contents, and all of its children by the given factor.
	public static void scaleViewAndChildren(View root, float scale)
	// Retrieve the view's layout information
	ViewGroup.LayoutParams layoutParams = root.getLayoutParams();
	// Scale the view itself
	if (layoutParams.width != ViewGroup.LayoutParams.FILL_PARENT &&
	layoutParams.width != ViewGroup.LayoutParams.WRAP_CONTENT)
	layoutParams.width *= scale;
	if (layoutParams.height != ViewGroup.LayoutParams.FILL_PARENT &&
	layoutParams.height != ViewGroup.LayoutParams.WRAP_CONTENT)
	layoutParams.height *= scale;
	// If this view has margins, scale those too
	if (layoutParams instanceof ViewGroup.MarginLayoutParams)
	ViewGroup.MarginLayoutParams marginParams =
	marginParams.leftMargin *= scale;
	marginParams.rightMargin *= scale;
	marginParams.topMargin *= scale;
	marginParams.bottomMargin *= scale;
	// Set the layout information back into the view
	// Scale the view's padding
	(int)(root.getPaddingLeft() * scale),
	(int)(root.getPaddingTop() * scale),
	(int)(root.getPaddingRight() * scale),
	(int)(root.getPaddingBottom() * scale));
	// If the root view is a TextView, scale the size of its text
	if (root instanceof TextView)
	TextView textView = (TextView)root;
	textView.setTextSize(textView.getTextSize() * scale);
	// If the root view is a ViewGroup, scale all of its children recursively
	if (root instanceof ViewGroup)
	ViewGroup groupView = (ViewGroup)root;
	for (int cnt = 0; cnt < groupView.getChildCount(); ++cnt)
	scaleViewAndChildren(groupView.getChildAt(cnt), scale);



You must LOGIN to add comments