gravity属性的意思可以说众所周知我就不介绍了。分享下我遇到的问题。先看代码吧。
问题是:gravity在父布局中控制子布局的位置和在子布局中layout_gravity控制子布局在父布局中的位置。
效果想让textview居屏幕中心。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</LinearLayout>
我们可以先在父布局中来控制子布局的位置。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</LinearLayout>
效果是:
既然我们在父布局中可以控制,那么在子布局呢?对于线性布局的排列方式我就不介绍了大家都知道。
接下里代码写写看:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/hello_world" />
</LinearLayout>
效果却是:
通过现象可以发现,子布局如果调整在父布局(针对线性布局)中的位置如果线性布局是水平的那么子布局layout_gravity=center效果只能垂直居中,如果是垂直的话,子布局是水平居中的。造成这种情况的原因是什么我不知道,如果有知道的不妨留个言。