如何以编程方式(动态)将LinearLayout置于RelativeLayout中心?

时间:2014-12-14 17:14:53

标签: android android-layout

我想在其RelativeLayout父级中动态居中一个LinearLayout视图,所以我想使用android.R.attr.layout_centerInParent。 我该如何申请? 我尝试了以下内容,但子视图根本没有出现。

子视图

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView android:id="@+id/text1"
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView android:id="@+id/text2"
        android:textSize="16sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

父视图

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center">

    <FrameLayout
        android:id="@+id/my_preview"
        android:layout_width="match_parent"
        android:layout_height="407dp" >
    </FrameLayout> 

    <include
        android:id="@+id/my_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="408dp"
        layout="@layout/my_bar" />

</RelativeLayout>

在我的活动中

            LayoutInflater inflater = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            RelativeLayout rootView = (RelativeLayout) inflater.inflate(id, null);
            LinearLayout textBox = (LinearLayout) inflater.inflate(R.layout.child_view, null);
            TextView line2 = (TextView) textBox.findViewById(R.id.text2);
            line2.setText("hahahaha");
            TextView line1 = (TextView) textBox.findViewById(R.id.text1);
            line1.setText("rrrrrrrrrr");
            RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
            rlp.addRule(android.R.attr.layout_centerInParent);                  
            textBox.setLayoutParams(rlp);
            rootView.addView(textBox);
            setContentView(rootView);

我将子视图更改为RelativeLayout但仍看不到子视图。

1 个答案:

答案 0 :(得分:1)

由于某种原因,android.R.attr.layout_centerInParent失败。 我用了

rlp.addRule(RelativeLayout.CENTER_IN_PARENT);   

它有效!