Android: setting width and height programatically
By admin
There are times when you need to change width and height of View elements you defined in your XML layout or you want to create elements dynamically.
In that case you need to grab the view element and changed its layoutParams. Like how it is done below:
LinearLayout layout = (LinearLayout)findViewById(R.id.layoutId);<br></br>ViewGroup.LayoutParams params = layout.getLayoutParams();<br></br>params.width = 200;<br></br>params.height = 200;<br></br>layout.setLayoutParams(params);
Notice that params.width values are in pixels. If you need your dimensions in DP or SP units you need to convert it.
For example, if you need width and height values in DP unit then you need to do something like:
final float scale = this.getResources().getDisplayMetrics().density; //
this is a reference to an Activity or Context<br></br>params.width = (int) (200 * scale + 0.5f);
For more information refer to documentation “Converting dp units to pixel units”: http://developer.android.com/guide/practices/screens_support.html