I have identified the width and height of the screen programatically. Now I want to use that width and height in my xml file. Kindly give me a way to achive this.
Here is my Activity class.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DisplayMetrics display = this.getResources().getDisplayMetrics();
float width = display.widthPixels;
float height = display.heightPixels;
Toast.makeText(TestProjectActivity.this, "width and height is: "+width + ": "+height, Toast.LENGTH_LONG).show();
float w = convertPixelsToDp(width, this);
float h = convertPixelsToDp(height, this);
Toast.makeText(TestProjectActivity.this, "DP" +w+": "+h, Toast.LENGTH_LONG).show();
}
public static float convertPixelsToDp(float px,Context context){
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float dp = px / (metrics.densityDpi / 160f);
return dp;
}
Now I want to send the w and b to the xml for the further work.
Any help would be appricieted?
Thanks.
You cannot pass information back to XML. At most, you can get your widget using
findViewByIdand then programmatically set the widget size.You should then use a
LinearLayoutto give your image a size relative to the available width (like a percentage of the width of the screenHere is how your XML would look (pseudo code)
In the above example, each image view will take 50% of the screen width, no matter the number of pixels.
I think you need to Google a good tutorial about layouts in Android.