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>

发现可能是由于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>

使用RelativeLayout布局后设置居中就可以了
感谢
如果对你有用,请点个爱心给个赞吧~~
网友评论