相对布局返回线性布局的布局参数。

7
这里是我的布局xml中定义RelativeLayout的代码片段。
<RelativeLayout
    android:id="@+id/npvirrButtons"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    >
    <Button
        android:id="@+id/buttonNPVLabel"
        android:layout_marginLeft="20dp"
        android:layout_alignParentLeft="true"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        />

    <Button
        android:id="@+id/buttonIRR_NFV"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        />

</RelativeLayout>

这里是我保存对它的引用的位置。
this.npvirrButtons = (RelativeLayout)this.findViewById(R.id.npvirrButtons);

后来当我试图将高度从0dp更改为wrap_content时,我这样获取布局参数:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)this.npvirrButtons.getLayoutParams();

但是我遇到了一个异常:

java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
    at com.mydomain.myapp.MyActivity.calculateIRR(MyActivity.java:564)

为什么我的RelativeLayout返回了一个LinearLayout参数对象?


尝试在删除gen和bin文件夹后重新运行项目。 - Ashish Rathee
1个回答

9

getLayoutParams() 方法返回视图相对于其父级的当前 LayoutParameters。因此,buttonIRR_NFV 将返回 RelativeLayout.LayoutParameter

可以这样理解:getLayoutParams() 是一个用来改变当前视图在容器中位置的方法。如果你想修改其中一个子视图的布局方式,需要获取它的 LayoutParameters。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接