美文网首页
Android LinearLayout中子控件layout_g

Android LinearLayout中子控件layout_g

作者: 使命初始 | 来源:发表于2021-01-28 13:50 被阅读0次

LinearLayout中子控件layout_gravity="center"无效 问题解决

在一些情况下,两个子控件,其中一个需要居中,另外一个在这个控件的后边
当时理所当然的默认使用了LinearLayout布局,想着设置成android:orientation="horizontal",然后其中一个控件居中即可
万万没想到居然不可以
代码如下:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginEnd="4dp"
            android:text="测试第一段"
            android:textColor="@android:color/background_light"
            android:textSize="22sp" />

        <TextView
            android:id="@+id/text2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="4dp"
            android:text="测试第二段"
            android:textColor="@android:color/background_light"
            android:textSize="22sp" />
    </LinearLayout>
失败示例.png

发现可能是由于LinearLayout布局设置成横置后,控件再设置成居中,就直接失效了,反正最后怎么调我也没有成功,最终换成了RelativeLayout布局

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_gravity="center"
            android:layout_marginEnd="4dp"
            android:text="测试第一段"
            android:textColor="@android:color/background_light"
            android:textSize="22sp" />

        <TextView
            android:id="@+id/text2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="4dp"
            android:layout_toEndOf="@id/text1"
            android:text="测试第二段"
            android:textColor="@android:color/background_light"
            android:textSize="22sp" />
    </RelativeLayout>
成功示例.png

使用RelativeLayout布局后设置居中就可以了

感谢

如果对你有用,请点个爱心给个赞吧~~

相关文章

网友评论

      本文标题:Android LinearLayout中子控件layout_g

      本文链接:https://www.haomeiwen.com/subject/minazktx.html