首先我们先来看一个例子,我们想要在一个布局文件中,使我们的一个TextView放在我们布局的中间我们需要怎么做呢,有几种方法呢:
首先我们想到的可能是这样的:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test" />
</LinearLayout>
但是结果呢:
可以看到我们想要的布局并没有出现。这里的问题在于什么地方呢:我们可以看到我们在LinearLayout的标签当中使用了layout_gravity="center"这里我们想要的是想让他下面的布局布局到中间,但是并没有实现。我们再试下另外一种:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test" />
</LinearLayout>
我们看下结果:
从这里我们可以看见我们的设置生效了。我们想要的样子出来了。
从这里我们大概可以看出gravity和layout_gravity的区别了:
layout_gravity指的是当前标签在父控件中的位置,
gravity指的是当前标签中的子控件或者是标签显示的内容处于的位置。