自己实现notifyDatasetChanged

本文介绍了如何在自定义的LinearLayout中实现类似ListView的Adapter功能,特别是如何在数据变化时调用notifyDataSetChanged进行更新。通过扩展LinearLayout,创建自定义Adapter,并结合DataSetObserver,实现了在数据集改变时动态更新视图,减少了不必要的视图添加和移除操作。
摘要由CSDN通过智能技术生成

今天这篇博客,我们来实现一下adapter那个最常用的notifyDatasetChanged功能,我们利用一个继承一个LinearLayout来实现一个可能在日常工作中很常用的功能。
大家在工作中可能经常遇到这样的功能:

需要定义一个列表来展示菜单,但是这个菜单并不一定适合ListView,然后,我们可能就通过一个LinearLayout来实现。

如何让我们的LinearLayout使用起来更像ListView呢? 那就是设置Adapter。那你的代码可能是这样的。
扩展LinearLayout:

public class MyLinearLayout extends LinearLayout {
   

    private Adapter mAdapter;

    public MyLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(VERTICAL);
    }

    public void setAdapter(Adapter adapter) {
        removeAllViews();
        mAdapter = adapter;
        int itemCount = mAdapter.getItemCount();
        View child;
        for (int i = 0; i < itemCount; i++) {
            child = mAdapter.getView(this, i);
            addView(child);
        }
    }
}

自己动手实现一个简单的Adapter:

public abstract class Adapter {
   
    public abstract int getItemCount();
    public abstract View getView(View parent, int position);
}

在我们的代码如何使用呢?
首先继承咱们定义的Adapter

public class MyAdapter extends Adapter {
   

    private ArrayList<String> mData;

    public MyAdapter(ArrayList<String> data) {
        mData = data;
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    @Override
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亓斌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值