尝试将布局重力设置为LinearLayout时ClassCastException

时间:2016-06-02 06:04:07

标签: android android-layout

我有一个用例,当我需要以编程方式将线性布局的重力更改为父级中心时。由于某种原因它崩溃了:

Non-fatal Exception: java.lang.ClassCastException
android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams

我有以下xml:

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:animateLayoutChanges="true"
        android:clickable="true"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@drawable/bg02" />

        <LinearLayout
            android:id="@+id/myLinearLayout"
            android:layout_width="300dp"
            android:layout_marginTop="30dp"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:orientation="vertical">

            ...

            ...

        </LinearLayout>

</RelativeLayout>

代码:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    params.weight = 1.0f;
                    params.gravity = Gravity.CENTER;

myLinearLayout.setLayoutParams(params);
  • 我也尝试将LinearLayout.LayoutParams更改为RelativeLayout.LayoutParams,因为我认为它应该相对于父本身(在这种情况下是RelativeLayout)但是并没有太大变化.. < / LI>

3 个答案:

答案 0 :(得分:1)

LinearLayout位于RelativeLayout内,因此必须为RelativeLayout.LayoutParams而不是LinearLayout.LayoutParams

答案 1 :(得分:0)

您需要添加 RelativeLayout Param 而不是 LinearLayout param ,而在RelativeLayout参数中,您需要添加规则,如下所示:

RelativeLayout.LayoutParams params = 
   new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, 
                                   RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
//params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
//params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

答案 2 :(得分:0)

Linearlayout是前一个响应者指出的RelayiveLayout的子级。如果要将线性布局置于relativelayout中心,可以按如下方式添加规则。

RelativeLayout.LayoutParams params = myLinearLayout.getLayoutParams();
params.addRule(RelativeLayout.CENTER_IN_PARENT);
myLinearLayout.setLayoutParams(params);

假设您希望linearlayout居中。如果没有,您可以找到适合您目的的规则。