Android include

更新时间:2021-12-29

    通过include可以重复使用某个布局,相同的页面不需要重复的去写了,复用。

1. 使用方式示例

1)创建一个layout,如:my_include_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@color/black">

    <TextView
        android:id="@+id/src_include_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="this is include"
        android:textColor="@color/white"
        android:textSize="30sp"
        />

</LinearLayout>

在这里插入图片描述

2)通过include重复使用上方的布局

在 activity_main.xml中通过include重复使用布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <include
        android:id="@+id/my_include_1"
        layout="@layout/my_include_layout" />

    <include
        android:id="@+id/my_include_2"
        layout="@layout/my_include_layout"
        />
</LinearLayout>

在这里插入图片描述

3)通过activity操作

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // id为include处设置的
        View include_1 = findViewById(R.id.my_include_1);
        View include_2 = findViewById(R.id.my_include_2);

        // 通过view去查找子控件
        TextView include_1_tv = include_1.findViewById(R.id.src_include_tv);
        TextView include_2_tv = include_2.findViewById(R.id.src_include_tv);

        // 给子控件TextView设置text
        include_1_tv.setText("new include1 text value");
        include_2_tv.setText("new include2 text value");
    }
}

4)效果

在这里插入图片描述

5)注意

当在include中添加如下代码,即增加 layout_margin 没有效果的

    <include
        android:id="@+id/my_include_2"
        layout="@layout/my_include_layout"
        android:layout_margin="10dp"
        />

如果要使用 标记来替换布局属性,您必须同时替换 android:layout_height 和 android:layout_width 才能让其他布局属性生效。
在这里插入图片描述
地址: https://developer.android.google.cn/training/improving-layouts/reusing-layouts

改为如下代码:

<include
    android:id="@+id/my_include_2"
    layout="@layout/my_include_layout"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_margin="10dp"
    />

效果如下:
在这里插入图片描述

2. 参考文档:

Re-using layouts with :https://developer.android.google.cn/training/improving-layouts/reusing-layouts

好记性不如烂笔头!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值