Android自定义组件,并把自定义组件和自定义xml布局文件关联

前言

在开发自定义view时,往往需要绑定xml布局文件,那具体怎么做呢?

自定义view和xml布局文件关联的思路是:在自定义view的构造函数中,通过LayoutInflater.from(context).inflate(R.layout.test_layout, this)关联xml布局文件。具体代码如下

1、代码

自定义布局——xml代码(test_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="match_parent">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

自定义组件——Java代码(TestView)

public class TestView extends LinearLayout {

    public TestView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    /**
     * 初始化组件
     * @param context
     */
    private void init(Context context) {

        //加载布局文件到此自定义组件
        //注意:第二个参数需填this,表示加载text_layout.xml到此自定义组件中。如果填null,则不加载,即不会显示text_layout.xml中的内容
        View view = LayoutInflater.from(context).inflate(R.layout.test_layout, this);

        //动态设置自定义xml中TextView的显示内容
        TextView title = view.findViewById(R.id.tv_title);
        title.setText("我是自定义标题");
    }
}

调用代码(activity_main.xml)

<?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"
    tools:context="com.fireflyh.demo.MainActivity"
    android:orientation="vertical">

    <com.fireflyh.demo.widget.TestView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></com.fireflyh.demo.widget.TestView>

</LinearLayout>

正文结束


2、坑

错误重现:

LayoutInflater.from(context).inflate(R.layout.test_layout, this);

写成了

LayoutInflater.from(context).inflate(R.layout.test_layout, null);

现象:自定义xml中的内容不显示在自定义组件中。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容