本文介绍了Android,以高度百分比添加视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在父视图中添加一个宽度为100%,X%(例如,使其变为40%)的视图

i wanna add a view with a 100% width and X%(e.g: lets make it 40%) to the parent view

我有这个:

private RelativeLayout getParentView(){
    return (RelativeLayout) MyActivity.this.getWindow().getDecorView().getRootView();
}

我应该将父视图强制转换为LinearLayout或RelativeLayout才能实现吗?

i should cast parent view to LinearLayout or RelativeLayout can achieve this ?

以及如何以编程方式设置"myView"宽度和高度百分比?

and how to set 'myView' width and height in percentage programmatically ?

谢谢

推荐答案

您可以通过简单地获取屏幕宽度来实现

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);

希望这会有所帮助.

这篇关于Android,以高度百分比添加视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 09:44