问题
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