LinearLayout中子控件layout_gravity="center"無效 問題解決
在一些情況下,兩個子控件,其中一個需要居中,另外一個在這個控件的后邊
當(dāng)時理所當(dāng)然的默認使用了LinearLayout布局,想著設(shè)置成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
發(fā)現(xiàn)可能是由于LinearLayout布局設(shè)置成橫置后,控件再設(shè)置成居中,就直接失效了,反正最后怎么調(diào)我也沒有成功,最終換成了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布局后設(shè)置居中就可以了
感謝
如果對你有用,請點個愛心給個贊吧~~