Android中对于布局的复用

本文介绍了在Android开发中实现布局复用的三种方法:自定义控件、XML include标签引用以及LayoutInflater动态加载布局。通过这些方式,开发者可以有效提高代码复用率,提升开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Android中,对于布局的复用,一般有三种:
一种是使用用代码写自定义控件,
一种是在xml布局文件中写布局,然后在要用到相同布局的时候,使用include 来引用布局;例如:

<include
        android:id="@+id/mylayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/myView1"
        layout="@layout/myview_layout"
        android:layout_marginTop="35dp" />

还有一种就是在xml中写好布局,然后在代码中写自定义布局的时候,使用LayoutInflater加载布局.
如:

package cn.com.cheng.layout_demo;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.RelativeLayout;

public class MyLayoutView extends RelativeLayout{

    public MyLayoutView(Context context) {
        this(context,null);
    }

    public MyLayoutView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MyLayoutView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.myview_layout, this);
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值