动态更改相对布局宽度和高度

Vik*_*war 16 android android-layout

嗨我在LinearLayout中使用以下布局结构

<TableLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <TableRow
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </TableRow>

    <TableRow
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/tv1"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:paddingLeft="10dp"
            android:textColor="#000" />

        <TextView
            android:id="@+id/tv2"
            android:layout_height="wrap_content"
            android:layout_weight="1.0"
            android:gravity="right"
            android:paddingRight="10dp"
            android:textColor="#000" />
    </TableRow>
</TableLayout>

<ImageView
    android:id="@+id/img1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center" />

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="320px"
    android:layout_height="320px"
    android:gravity="center" >
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

并且想要从java文件中动态设置相对布局的宽度和高度,而不是在xml文件中将其设置为320px但不能这样做,因为我将限制仅限于纵向模式,因此方向更改不是问题.可以使用match_parent在全屏幕上设置相对布局,但我必须在屏幕上放置另一个视图,这样才有可能,或者我必须以另一种方式实现它...

Eri*_*ric 25

wrap_content一旦显示,Android不会刷新视图的布局.即使有invalidate()requestLayout().因此,如果您添加子视图或动态修改内容,则会被搞砸.

getLayoutParams().height = x 再加上requestLayout() 是一个很好的解决方案,如果你知道"X",如果你需要做的只有一次.在此之后,wrap_contentLayoutParams丢失了,因为你已经覆盖它.

为了解决这个问题,我编写了一个静态类,它重新计算大小并强制更新视图的布局wrap_content.使用的代码和说明可在此处获得:

https://github.com/ea167/android-layout-wrap-content-updater

请享用!


小智 17

尝试使用这个

getLayoutParams().height= x;
requestLayout(); or invalidate(); 
Run Code Online (Sandbox Code Playgroud)


KDe*_*kar 6

给.xml中的相对布局赋一个id:

android:id="@+id/relativelayout"
Run Code Online (Sandbox Code Playgroud)

现在在你的java文件中写这个:

RelativeLayout Rl = (RelativeLayout) findViewById(R.id.relativelayout);

RelativeLayout.LayoutParams layout_description = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT or YourUserDefinedwidth,
                        RelativeLayout.LayoutParams.FILL_PARENT or YourUserDefinedHeight);

Rl.setLayoutParams(layout_description);
Run Code Online (Sandbox Code Playgroud)