Yes i have got the cure to your problem, you are right i personally think that making layouts for every screen resolution is time taking and making your project size go big.
To make a layout that fits across all screen resolution i have implemented my own technique i.e setting width and height in terms of percentage
The Problem occurs when we set Views/Layouts
with some constant width or height value lets say 100dp
.
Solution is quite simple try to use match_parent
so that the view fill up empty space or use weight
and define every View
relative to other Views
this will help your layout to look good in almost every screen resolutions and at run time set LayoutParams
of only those Views/Layouts
that has some constant width or height in terms of Percentage.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/mLayout"
android:layout_width="280px"
android:layout_height="300px" />
</RelativeLayout>
Notice: I have used px for fixed sized layout's width/height because in LayoutParams layoutParams = new LayoutParams(int width, int height);
the width
and height
take value as pixels
Here is an example code
final ViewTreeObserver mLayoutObserver = mLayout.getViewTreeObserver();
mLayoutObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
DisplayMetrics metrics = getResources().getDisplayMetrics();
int deviceWidth = metrics.widthPixels;
int deviceHeight = metrics.heightPixels;
float widthInPercentage = ( (float) 280 / 320 ) * 100; // 280 is the width of my LinearLayout and 320 is device screen width as i know my current device resolution are 320 x 480 so i'm calculating how much space (in percentage my layout is covering so that it should cover same area (in percentage) on any other device having different resolution
float heightInPercentage = ( (float) 300 / 480 ) * 100; // same procedure 300 is the height of the LinearLayout and i'm converting it into percentage
int mLayoutWidth = (int) ( (widthInPercentage * deviceWidth) / 100 );
int mLayoutHeight = (int) ( (heightInPercentage * deviceHeight) / 100 );
LayoutParams layoutParams = new LayoutParams(mLayoutWidth, mLayoutHeight);
mLayout.setLayoutParams(layoutParams);
}
});
I guess the code is pretty much self explanatory if any one still need help you can ask right away
Conclusion: If you need to set some constant width/height for your Views/Layouts
always set value in px in layout file (i.e xml) and then programmatically set LayoutParams
.
Suggestion: I think Google Android Guys should seriously think of replacing the dp/dip
units to percentage
.