Android XML 布局基础(三)LayoutParams 布局参数

732 阅读1分钟

一、简介

二、xml代码 写法

  • layout_xxx 布局属性:

    <TextView
        android:layout_width="100dp"
        android:layout_height="200dp"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="10dp"
        android:text="Hello world!"
        android:textSize="10sp" />
    
  • ViewGroup 类会实现一个扩展 ViewGroup.Layoutparams 的嵌套类,里面包含一些设置视图 view 的尺寸和位置的属性。

    image.png

    // 创建视图
    TextView tv = new TextView(this);
    // 创建布局模块(可以认为它才是根视图,只有在它身上才能生效布局参数)
    LinearLayout layout = new LinearLayout(this);
    // 获取视图中的布局参数对象
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
    // 配置布局属性
    params.leftMargin = 30; // 左边距
    params.topMargin = 30;  // 上边距
    params.width = 100;     // 宽
    params.height = 200;    // 高
    // 将配置好的布局参数设置到视图中
    tv.setLayoutParams(params);
    // 将视图模块添加到布局模块中
    layout.addView(tv);
    

三、属性

  • 一般而言,建议不要使用绝对单位(如像素 px)来指定布局宽度和高度,最好是使用相对测量单位(如与密度无关的像素单位 dpwrap_contentmatch_parent),有利于确保应用在各类尺寸的设备屏幕上正确显示。

  • wrap_content:视图将其大小调整为内容所需要的尺寸。

  • match_parent:视图尽可能采用其父视图组所允许的最大尺寸。

四、案例

  • xml 布局代码

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <!-- 由于最外层不是 Layout,则这里为根布局 -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#ffc">
            <!-- 再添加一个内部视图布局 -->
            <LinearLayout
                android:layout_marginTop="200dp"
                android:layout_marginLeft="70dp"
                android:layout_width="300dp"
                android:layout_height="300dp"
                android:background="#fcf">
                <!-- 添加视图组件 -->
                <TextView
                    android:id="@+id/dzm"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="100dp"
                    android:layout_marginTop="200dp"
                    android:text="DZM TEST"
                    android:textSize="20sp" />
            </LinearLayout>
        </LinearLayout>
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • 效果

    image.png