【Android(安卓)开发】:Android布局中的几种常用属性
1. 为了适应各种界面风格,Android提供了5种布局,这5种布局分别是:
1) 线性布局: LinearLayout
2) 帧布局: FrameLayout
3) 相对布局: RelativeLayout
4) 表格布局: TableLayout
5) 绝对布局: AbsoluteLayout
上面这五种布局,每一种布局都可以去嵌套使用,利用以上5种布局我们可以再手机屏幕上随心所欲的摆放各种控件。然后在应用程序中使用findViewById()方法来使用控件,需要注意的是使用findViewById之前需要使用setContentView先加载xml文件、布局文件会抛出异常信息。也就是说findViewById方法要在setContentView之后才能使用
2. Android表示单位长度的方式
1) px:表示屏幕实际的象素。例如,320*480的屏幕在横向有320个象素,在纵向有480个象素. [比较少用]
2) dp(dip): 是屏幕的物理尺寸。大小为1英寸的1/72。
3) sp(与刻度无关的像素):与dp类似,但是可以根据用户的字体大小首选项进行缩放. [描述字体的时候应该是使用sp]
[使用技巧]:
1) 如果设置表示长度、高度等属性时可以使用 dp 或 sp。但如果设置字体,需要使用sp。
2) dp是与密度无关,sp除了与密度无关外,还与scale无关
3) 如果使用dp和sp,系统会根据屏幕密度的变化自动进行转换
3. 布局中的常用属性介绍
1) layout_margin:是控件边缘相对于父控件的边距,如下图所示:
2) layout_padding是控件内容相对于控件边缘的边距,如下图所示:
3) android:gravity: 用于设置View组件的对齐方式,例如:文本在按钮中的位置
4) android:layout_gravity: 用于设置Container组件的对齐方式,例如:带文本的按钮在容器中的位置
程序Demo:
Layout布局文件如下所示:
<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="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".LayoutDemo" > <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="100dp" android:layout_marginLeft="40dp" android:layout_marginRight="60dp" android:layout_marginTop="30dp" android:text="测试按钮一" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="20sp" android:paddingTop="5sp" android:text="测试按钮二" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="测试按钮三" /> <Button android:id="@+id/button4" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="right" android:text="测试按钮四" /></LinearLayout>
更多相关文章
- Android(安卓)UI控件之RadioGroup、RadioButton
- 关于WindowManager在Android(安卓)N和Android(安卓)N以下表现差
- Android(安卓)中的ellipsize
- Android桌面应用
- [置顶] 对Android(安卓)MVVM的理解
- Android(安卓)Notification 用法的4种形式
- Android软件开发常用系统控件(一) TextView
- Android定制ListView的界面(使用继承自ArrayAdapter的自定义适配
- android基础控件学习学习(1)【入门篇】