RecyclerView是什么
RecyclerView与ListView 有什么不同
RecyclerView与ListView 对比浅析:缓存机制
使用RecyclerView展示列表的步骤
- 在build.gradle中引用
implementation 'androidx.recyclerview:recyclerview:1.1.0'
- 在布局中申明
<androidx.recyclerview.widget.RecyclerView android:id="@+id/history_listview"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="@color/color_000000_10"
android:dividerHeight="0dp"
android:fitsSystemWindows="true"
tools:context="com.idoucx.timething.activity.HistoryListActivity"
app:layoutManager="LinearLayoutManager"
tools:listitem="@layout/layout_history" />
注意布局中设置布局中的的layoutManager
<!--app后面用于设置LayoutManager-->
xmlns:app="http://schemas.android.com/apk/res-auto"
app:layoutManager="LinearLayoutManager"
否则就会不展示Layout
RecyclerView: No layout manager attached; skipping layout
也可以通过代码指定:
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
- 新建
Adapter
类继承自RecyclerView.Adapter<T>
class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.ViewHolder> {
}
2.1 添加构造方法
HistoryAdapter(HistoryListActivity parent,
List<RecordInfo> items,
boolean twoPane) {}
2.2 实现onCreateViewHolder和创建ViewHodler 加载布局文件,将View和ViewHolder绑定
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_history, parent, false);
return new ViewHolder(view);
}
这里ViewHolder的要继承自 RecyclerView.ViewHolder
class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.history_item_day)
TextView dayTv;
@BindView(R.id.history_item_color_view)
TextView colorView;
@BindView(R.id.history_item_content_tv)
TextView contentTv;
@BindView(R.id.history_item_time_tv)
TextView timeTv;
@BindView(R.id.history_item_line1)
TextView line1;
@BindView(R.id.history_item_line2)
TextView line2;
@BindView(R.id.history_item_delete)
MaterialButton deleteBtn;
ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
2.3 实现getItemCount()
,得到子项的个数
public int getItemCount() {
LogUtil.e("本次展示的大小是:>"+mRecordInfos.size());
return mRecordInfos.size();
}
2.4 实现onBindViewHolder(@NonNull ViewHolder holder, int position)
方法,将数据和viewHolder绑定,数据怎么展示,展示的逻辑是什么都写到这里
- 将Adapter和RecyclerView绑定
adapter = new HistoryAdapter(this,recordInfos,false);
recyclerView.setAdapter(adapter);
网友评论