Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, add view with height in percentage

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

like image 979
Mars Avatar asked Sep 01 '25 18:09

Mars


1 Answers

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.

like image 79
Sarthak Gandhi Avatar answered Sep 04 '25 08:09

Sarthak Gandhi