返回

使用Databinding快速打造仿携程app筛选控件(二)

Android

使用Databinding快速打造仿携程app筛选控件(二)

背景介绍

在上一篇博文中,我们介绍了只用Databinding的方式快速实现了一个主从联动的组合自定义控件。在这篇博文中,我们将实现一个无限扩展的组织树控件。

特点介绍

我们的组织树控件具有以下特点:

  • 开箱即用:您可以直接在您的项目中使用它,而不需要进行任何复杂的配置。
  • 支持各个层级样式自定义:您可以自定义控件的各个层级的样式,以满足您的项目需求。
  • 可以自由加载不同的xml:您可以自由加载不同的xml文件来定义控件的结构和样式,从而实现不同的组织树控件。

实现步骤

1. 创建布局文件

首先,我们需要创建一个布局文件来定义控件的结构。您可以使用以下代码来创建布局文件:

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>

        <variable
            name="organizationTree"
            type="com.example.OrganizationTree" />

    </data>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/organization_tree_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</layout>

2. 创建自定义控件

接下来,我们需要创建一个自定义控件来实现组织树控件。您可以使用以下代码来创建自定义控件:

public class OrganizationTree extends LinearLayout {

    private RecyclerView recyclerView;
    private OrganizationTreeAdapter adapter;

    public OrganizationTree(Context context) {
        super(context);
        init(context);
    }

    public OrganizationTree(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public OrganizationTree(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        inflate(context, R.layout.organization_tree, this);

        recyclerView = findViewById(R.id.organization_tree_recycler_view);
        adapter = new OrganizationTreeAdapter(context);
        recyclerView.setAdapter(adapter);
    }

    public void setOrganizationTreeData(List<OrganizationTreeData> data) {
        adapter.setData(data);
    }

}

3. 创建自定义适配器

最后,我们需要创建一个自定义适配器来为组织树控件提供数据。您可以使用以下代码来创建自定义适配器:

public class OrganizationTreeAdapter extends RecyclerView.Adapter<OrganizationTreeAdapter.ViewHolder> {

    private List<OrganizationTreeData> data;

    public OrganizationTreeAdapter(Context context) {
        data = new ArrayList<>();
    }

    public void setData(List<OrganizationTreeData> data) {
        this.data = data;
        notifyDataSetChanged();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.organization_tree_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void