美文网首页我爱编程
Android自定义组件,并把自定义组件和自定义xml布局文件关

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

作者: 萤火虫叔叔 | 来源:发表于2018-01-15 15:22 被阅读586次

前言

在开发自定义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中的内容不显示在自定义组件中。

相关文章

网友评论

    本文标题:Android自定义组件,并把自定义组件和自定义xml布局文件关

    本文链接:https://www.haomeiwen.com/subject/jxfdoxtx.html