今天这篇博客,我们来实现一下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