【Android学习】【include】控件使用

在Android中,【include】控件可以将一个xml文件插入到另一个XML文件中,对于重复性的布局可以节省代码,在使用【include】之后,获取【include】里面的布局控件的操作为

被插入的xml代码

<RelativeLayout 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"
    tools:context=".fragment.HomeFragment">
    
    <!--添加ID和布局-->
<include android:id="@+id/ll_include" layout="@layout/view_top_include" />

</RelativeLayout>

view_top_include的代码:

<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
    android:gravity="center"
    android:background="@color/colorPrimary"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/iv_admin"
        android:layout_width="@dimen/dp_40"
        android:layout_height="@dimen/dp_40"
        android:layout_marginStart="@dimen/dp_10"
        android:background="@drawable/ic_baseline_account_circle_24"
        android:padding="@dimen/dp_10" />

    <TextView
        android:id="@+id/tv_admin"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/dp_10"
        android:layout_weight="1"
        android:text="admin"
        android:textColor="@color/cBlack"
        android:textSize="@dimen/sp_14"
        android:textStyle="normal" />

    <ImageView
        android:id="@+id/iv_upload_view"
        android:layout_width="@dimen/dp_40"
        android:layout_height="@dimen/dp_40"
        android:layout_marginEnd="@dimen/dp_10"
        android:background="@drawable/ic_baseline_circle_up_24"
        android:padding="@dimen/dp_10"
        tools:ignore="RtlSymmetry" />
</LinearLayout>

使用方式

  //【include】的XML布局根布局为LinearLayout
  lateinit var ll_include: LinearLayout
  lateinit var tv_admin: TextView
  lateinit var iv_upload_view: ImageView
  
  //首先需要获取【include】的控件ID,进行初始化
  ll_include = findViewById(R.id.ll_include)
  
  //【include】布局里面的控件通过【include】的控件ID进行获取和初始化
  tv_admin = ll_include.findViewById(R.id.tv_admin)
  iv_upload_view = ll_include.findViewById(R.id.iv_upload_view)
  

你可能感兴趣的:(Android学习笔记,android)