安卓学习(初)第三章(2)(《第一行代码》)

一、布局的线性布局<LinearLayout

1、示例:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
      ……
     />
   <Button
      ……
     />
    …… ……
</LinearLayout>

这样写,布局就会出现水平排列的一行按键。如果android:orientation="horizontal"改成android:orientation="vertical",则就会出现一列按键。这分为水平排列方式、垂直排列方式就所谓的线性布局。

2、用垂直还是水平排列的方式(android:orientation设置为"horizontal"或"vertical")都不能同时把控件大小设置为"match_parent"。

3、此时的控件对齐方式(用android:layout_gravity指定)根据android:orientation设置不同有不同限制。如是水平排列,控件的对齐方式就不能设置水平方向对齐方式了,垂直排列也同理。而控件对齐方式的选择和文本对齐方式android:gravity的一样(见之前的笔记)。

4、android:layout_weigh用法

用了线性排列方式后,可以通过android:layout_weigh=来调多个控件各自占空间的比例。如有两个控件,其中一个指定android:layout_weigh="1";另一个指定android:layout_weigh="3",用水平排列方式(android:orientation="horizontal"),那么结果就是这两个控件以水平方式排列,且占空间位置是1:3。若是水平排列,用了android:layout_weigh=这个指定后,宽度就不用指定了,若是垂直排列则在这指定下高度就不用指定了。此外如果有多个控件,只有其中几个指定了android:layout_weigh,其他控件独立指定了宽和高,那么布局就会让独立指定大小的控件占好位置和空间再让其中指定了android:layout_weigh的控件按指定值以比例瓜分空间。

二、相对布局<RelativeLayout

1、相对于父布局进行定位。如:android:layout_alignParentLeft="true"表示靠左;android:layout_alignParentTop="true"表示置顶;android:layout_alignParentBottom="true"表示置底,这几个指定可以按逻辑两个组合混合用。android:layout_centerInParent这个是表示居中(屏幕正中间),单独使用。

2、相对于控件进行定位。如:android:layout_above="@+id/button1"表示该控件位于button1的正上方,指定的是一个控件的id。同理还有android:layout_below="@+id/button1"、android:layout_toLeft0f="@+id/button1"等。此外,android:layout_alignbelow="@+id/button1"表示该控件的上边缘和button1的下边缘对齐android:layout_alignLeft="@+id/button1"表示和button1的左边缘对齐,以此类推。注意!引用一个控件的id时,该控件一定要在引用控件的后面(和C语言的函数调用和嵌套类似的死规则)。

三、帧布局<FrameLayout

1、在完成各个控件的基础属性设置情况下,该布局方式会默认所有控件在屏幕的左上角显示,后来的控件覆盖在先来的控件上。

2、帧布局一样可以用layout_gravity属性来逐个指定控件的在布局中的对齐方式。

四、百分比布局<android.support.percent.PercentFrameLayout或<android.support.percent.PercentRelativeLayout

1、不同于之前的三种布局,由标签名称可以猜到该布局是对FrameLayout和RelativeLayout这两种布局的功能拓展。这种布局中可以不再使用wrap_content等方式来指定控件的大小而是允许直接指定控件在布局中占的百分比。

2、首先要在app/build.gradle文件的dependencies代码闭包内添加这个依赖:compile'com.android.suppport:percent:24.2.1'

3、该布局方式的控件大小设置方式如:app:layout_widthPercent="50%"   app:layout_heightPercemt="50%",表是宽高都占屏幕的50%。此时的控件对齐方式和前面三种布局一样写法。注意!<android.support.percent.PercentFrameLayout的会继承<FrameLayou所有特性,<android.support.percent.PercentRelativeLayout会继承<RelativeLayou所有特性。

*4、老版本的Android Studio用百分比布局没有写android:layout_width等这些指定控件高和宽大小的代码会提示错误,我们直接忽略就行,不影响程序运行。

猜你喜欢

转载自blog.csdn.net/Entronk_star/article/details/81748999