ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# notifyDataSetChanged 不生效原因 1、在子线程调用 2、数据源引用对象发生变更 # ListView中的Adapter ListView中的Adapter示例如下: ```java public class StudentAdaper extends ArrayAdapter<Student> { public StudentAdaper(Context context, int resourceId, List<Student> studentList) { super(context, resourceId, studentList); } @Override public View getView(int position, View convertView, ViewGroup parent) {} @Override public int getItemViewType(int position) {} @Override public int getViewTypeCount() {} static class ViewHolder {} } ``` 其中getView()方法会在item显示在屏幕上时进行调用。比如共100个item要显示,但屏幕高度只可以展示10个item,一开始getView()方法会调用10次,滑动界面时,每当有item展示时,再调用相应的getView()方法。 ## ListView的优化 ### Adapter优化 Layout的inflate()方法和findViewById()方法都是消耗资源的工作,在ListView快速滑动时,会消耗大量资源。所以引入ConvertView和ViewHolder来对布局和View进行缓存。 ```java @Override public View getView(int position, View convertView, ViewGroup parent) { Student student = getItem(position); View view; ViewHolder viewHolder; if (convertView == null) { view = LayoutInflater.from(mContext).inflate(mResourceId, parent, false); viewHolder = new ViewHolder(); viewHolder.name = view.findViewById(R.id.tv_name); viewholder.mark = view.findViewById(R.id.tv_mark); view.setTag(viewHolder); } else { view = convertView; viewHolder = (ViewHolder)view.getTag(); } viewHolder.name.setText(student.getName()); viewHolder.mark.setText(student.getMark()); return view; } ``` # RecyclerView中的Adapter RecyclerView中的Adapter示例如下: ```java public class StudentAdaper extends RecyclerView.Adapter<StudentAdapter.ViewHolder> { public StudentAdapter() {} @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {} @Override public void onBindViewHolder(ViewHolder holder, int position) {} @Override public int getItemCount() {} @Override public int getItemViewType() {} static class ViewHolder {} } ``` 其中,屏幕高度只可以展示10个item时,会调用10次onCreateViewHolder,来创建ViewHolder,上下滑动时ViewHolder可以缓存。当item出现(或将要出现在屏幕)时会调用onBindViewHolder,对ViewHolder进行填充。 ## RecyclerView的解耦性 * RecyclerView负责View的回收与复用 * LayoutManager负责View的布局管理 * ItemAnimator负责添加删减动画展示 * ItemDecoration负责分割线显示