【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>




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值