动态更改相对布局的宽度和高度 [英] Change Relative layout width and height dynamically
问题描述
我在LinearLayout中使用以下布局结构
Hi i am using following layout structure inside 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>
,并且想从Java文件动态设置相对布局的宽度和高度,而不是在xml文件中将其设置为320px,但不能做到这一点,方向更改不是问题,因为我将其限制为仅在纵向模式下使用.可以通过使用match_parent在全屏上设置相对布局,但是我必须在屏幕上放置另一个视图,所以有可能还是我必须以另一种方式实现它...
and want to set relative layout width and height dynamically from java file instead of setting it to 320px in the xml file but not able to do that , Orientation change is not an issue for as i restricting it to only in Portrait mode. It is possible to set the relative layout on full screen by using match_parent but i have to put another views on the screen so is it possible or i have to achieve it another way...
推荐答案
显示后,Android不会使用wrap_content
刷新视图的布局.
即使使用invalidate()
或requestLayout()
.
因此,如果您添加子视图或动态修改内容,则会很麻烦.
Android does NOT refresh layout of views with wrap_content
once it has been displayed.
Even with invalidate()
or requestLayout()
.
So if you add a child view, or modify the content dynamically, you're screwed.
getLayoutParams().height = x
加requestLayout()
是一个很好的解决方案.
之后,LayoutParams
中的wrap_content
丢失了,因为您已覆盖它.
getLayoutParams().height = x
plus requestLayout()
are a good solution if you know the "x", and if you need to do it ONLY ONCE.
After that the wrap_content
in LayoutParams
is lost, since you have overridden it.
为解决这个问题,我编写了一个静态类,该类重新计算大小并使用wrap_content
强制更新视图的布局.此处提供了代码和使用说明:
To solve that, I've written a static class that recomputes the sizes and forces the update of the layout for the views with wrap_content
. The code and instructions to use are available here:
https://github.com/ea167/android-layout-wrap-content-updater
享受!
这篇关于动态更改相对布局的宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!