【发布时间】:2013-03-15 05:08:24
【问题描述】:
您好,我在 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 在全屏上设置相对布局,但我必须在屏幕上放置另一个视图,所以有可能还是我必须以另一种方式实现它...
【问题讨论】:
-
要动态设置布局宽度,您必须从您创建的类扩展 RelativeLayout 类并覆盖 onMeasure 方法
-
感谢您的回复,我已经尝试了所有方法,当我尝试动态设置宽度和高度时,它给出了类转换异常。相对布局还包含其他子视图作为图像视图,因此我将其作为 Java 文件中的视图组,但无法做到这一点。
-
请贴出异常及其指向的代码
-
这是代码.. ViewGroup container = (ViewGroup) this.findViewById(R.id.containerr);我正在以 ViewGroup 的形式访问该相对布局,其中 containerr 是 xml 文件中相对布局的 ID。
-
如果我将 layoutparams 设置为容器,它会显示错误.. Java.lang.ClassCastException:RelativeLayout&LayoutParams cannot be cast to LinearLayout&LayoutParams