i wanna add a view with a 100% width and X%(e.g: lets make it 40%) to the parent view
i have this:
private RelativeLayout getParentView(){
return (RelativeLayout) MyActivity.this.getWindow().getDecorView().getRootView();
}
i should cast parent view to LinearLayout or RelativeLayout can achieve this ?
and how to set 'myView' width and height in percentage programmatically ?
Thanks
You can do this by simply getting the screen width
public static int getScreenWidth(Context context) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.widthPixels;
}
Multiply that by the percentage and give the parameters to view like this:
//For 40% height according to the screen width.
view.getLayoutParams().height = (int) (getScreenWidth(mContext) * 0.40);
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With