将视图置于包含另一个视图的LinearLayout内

时间:2016-01-26 13:48:33

标签: android xml android-layout android-linearlayout android-xml

这是LinearLayout的xml,它包含两个Views:

<RelativeLayout
        android:id="@+id/addItems"
        style="@android:style/Widget.ImageButton"
        android:layout_weight="5"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="@drawable/add_product_selector"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:padding="10dp" >

        <ImageView
            android:id="@+id/addIcon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:background="@drawable/mbs_add_blue"
            android:layout_marginLeft="45dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/addIcon"
            android:paddingLeft="5dp"
            android:text="@string/add_product"
            android:textSize="18dp"
            android:textColor="@color/black"
            android:textStyle="bold" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/startDictation"
        style="@android:style/Widget.ImageButton"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:background="@drawable/add_product_selector"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:padding="10dp">

        <ImageView
            android:id="@+id/recordIcon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:src="@drawable/microphone"
            android:scaleType="fitCenter"/>
    </RelativeLayout>

</LinearLayout>

它产生了这个输出:

enter image description here

因为我需要以编程方式将第二个RelativeLayout(id = startDictation)设置为&#34;去掉#34;在某些情况下,我希望第一个RelativeLayout(id = addItems)及其子项也在这些情况下居中。

因为我定义了layout_marginLeft =&#34; 45dp&#34;在第一个ImageView(id = addIcon)上,当第二个RelativeLayout(id = startDictation)消失时,我应该更改它以保持ImageView居中。

我必须在布局中更改某些内容,因为如果我删除layout_marginLeft =&#34; 45dp&#34;它现在会生成此输出从第一个ImageView(id = addIcon):

enter image description here

4 个答案:

答案 0 :(得分:1)

问题解决了,在ImageView中设置了可见性,而不是在RelativeLayout

答案 1 :(得分:0)

为什么不使用setVisibility(View.INVISIBLE)代替View.GONE

答案 2 :(得分:0)

你尝试过使用android:layout_gravity =“center_vertical”吗?您可以在里面选择不同的值。

答案 3 :(得分:0)

尝试以编程方式设置布局重力。当你调用startDictation visibilty去使用这段代码时

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

addItems.setLayoutParams(params);

当你看到你的起始布局

时,也不要忘记重新排列参数