ViewGroup相当于是一个放置View的容器,里面可以放置其他的View,如TextView,ImageView等等
大家可以先观察下面这段代码
这段代码 LinearLayout 布局就相当于一个ViewGroups ,里面的两个TextView就相当于是LinearLayout的子View ,LinearLayout就是父View(放置View的容器)
LinearLayout又称为线性布局,这个布局会将它所包含的控件在线性方向上依次排列 下面是LinearLayout布局的代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Google"
android:textSize="22sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="study Jams"
android:textSize="22sp"/>
</LinearLayout>
相信大家通过看这段代码,大部分的内容都可以看懂,只有在这一行的时候有所疑问android:orientation=”vertical”我们通过查文档得知
android:orientation=”“属性指定了排列的方向,vertical垂直排列,horizontal水平排列 这是上面代码呈现出来的视图
如果将android:orientation=”vertical”改为horizontal视图会是什么样?
下面为大家介绍设置宽度高度的两种属性 wrap_content 和match_parent,当我们直接设置View宽度时,因为不知道内容多少,很容易造成内容的损失,如下图的第一种,所以我们一般使用其余的两种属性、wrap_context 适合内容大小的宽度,View包含内容|match_parent 与父视图的宽度相同,如下图所示
接下来我们学习LinearLayout中的一个重要属性android :layout_weight.这个属性允许我们使用比例的方式来指定控件的大小 权重的默认大小为0,当我们不设置时,该View的权重就为0. 如何使用权重? 首先我们需要把使用权重的高度/宽度设置为0dp,使用权重控制大小。 下面的代码和呈现是我们不使用权重时的
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#f00"
android:text="Google"
android:textSize="22sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="study Jams"
android:background="#0f0"
android:textSize="22sp"/>
</LinearLayout>
下来我们使用权重,将第一个TextView的layout_width设置为0dp,layout_weight=1,得到如下图示
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#f00"
android:text="Google"
android:textSize="22sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="study Jams"
android:background="#0f0"
android:textSize="22sp"/>
</LinearLayout>
LinearLayout就为大家介绍到这里了 很感谢Google Study Jams的活动,推动我的学习