Android, add view with height in percentage

可紊 提交于 2019-12-11 05:42:06

问题


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


回答1:


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.




回答2:


private static void updateDimen(Activity activity){
    DisplayMetrics displayMetrics = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    screenHeight = displayMetrics.heightPixels;
    screenWidth = displayMetrics.widthPixels;
}

Use above code to get screen height and screen width.

Then get the instance of your Layout, get its LayoutParams instance and update the dimension

params.height = screenHeight * 0.6;
params.width = screenWidth * 0.6;


来源:https://stackoverflow.com/questions/45978491/android-add-view-with-height-in-percentage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!