android RelativeLayout以编程方式更改高度

时间:2014-09-26 11:02:23

标签: android android-scrollview android-relativelayout

我尝试以编程方式更改布局高度。我有两个按钮。在一个按钮中我改变了我的布局位置和第二个按钮我试图接收保存位置,这是我第一次。

<RelativeLayout
    android:id="@+id/popaplayout"
    android:layout_width="fill_parent"
    android:layout_height="200dp" >

这是我的布局 在我写的第一个按钮

RelativeLayout.LayoutParams parms = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.FILL_PARENT,
                    RelativeLayout.LayoutParams.FILL_PARENT);
parms.addRule(RelativeLayout.BELOW, R.id.movies_title_layout);
scrollpopap.setLayoutParams(parms);
scrollpopap.setScrollingEnabled(true);

和第二个按钮

RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, 300);
rel_btn.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
scrollpopap.setLayoutParams(rel_btn);
scrollpopap.setScrollingEnabled(false);

xml文件中,我写了200dp的高度,编程为300,并且有不同的高度。我怎样才能以编程方式编写保存高度?

如果有人知道解决方案,请帮助我 感谢

4 个答案:

答案 0 :(得分:40)

首先将 200 dp 转换为像素 -

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (200 * scale + 0.5f);

然后以编程方式设置,

RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, pixels);
            rel_btn.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            scrollpopap.setLayoutParams(rel_btn);
            scrollpopap.setScrollingEnabled(false);

答案 1 :(得分:26)

像这样将DP转换为PX。

final float scale = getContext().getResources().getDisplayMetrics().density;
int px = (int) (100 * scale + 0.5f);  // replace 100 with your dimensions

设置相对布局的一些layout_gravity。并通过java代码更改高度和宽度。

RelativeLayout rl = (RelativeLayout) findViewById(R.id.yourId);
rl.getLayoutParams().height = px;  
rl.getLayoutParams().width = px;

答案 2 :(得分:4)

如果您打算更改RelativeLayout身高,请提供此帮助。

RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.yourId);
relativeLayout.getLayoutParams().height = 100;
relativeLayout.getLayoutParams().width = 100;

答案 3 :(得分:3)

使用此

RelativeLayout layout = (RelativeLayout) findViewById(R.id.yourlayout_id);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
params.height = 320;
params.width = 320;