步骤
1.列表项布局文件item.xml
2.数据类Item.java
3.适配器RecycleviewAdapter.java + ItemHolder内部类
4.配置activity.java+layout.xml:设置布局管理器+适配器+绑定数据
Item.java
public class MyItem {
private String mStatus;
public MyItem(String status, String title, String date, String time) {
this.mStatus = status;
//...
}
public String getmStatus() {
return mStatus;
}
public void setmStatus(String mStatus) {
this.mStatus = mStatus;
}
//...
}
item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/tv_state"
android:layout_width="120dp"
android:layout_height="88dp"
android:text="..." />
//...
RecycleviewAdapter.java
public class RecycleviewAdapter extends RecyclerView.Adapter<RecycleviewAdapter.ItemHolder> {
private List<MyItem> mMyItems;//数据
//适配器构造方法
public RecycleviewAdapter(List<MyItem> myItems){
this.mMyItems = myItems;
}
//用于界面填充item
@NonNull
@Override
public ItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ItemHolder(LayoutInflater.from(parent.getContext()).
inflate(R.layout.item,parent,false));
}
//用于item填充数据
public void onBindViewHolder(@NonNull ItemHolder holder, int position) {
holder.tv_state.setText(mMyItems.get(position).getmStatus());
}
@Override
public int getItemCount() {
return mMyItems.size();
}
//item管理器,用于管理item里面的控件
class ItemHolder extends RecyclerView.ViewHolder{
TextView tv_state;
//...
public ItemHolder(@NonNull View itemView) {
super(itemView);
tv_state = itemView.findViewById(R.id.tv_state);
//...
}
}
}
activity_list.xml
//...
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycleview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
//...
ListActivity.java
public class ListActivity extends AppCompatActivity {
private RecyclerView recyclerView;//RecyclerView
private LinearLayoutManager linearLayoutManager;//布局管理器
private RecycleviewAdapter recycleviewAdapter;//适配器
private List<MyItem> mData;//数据
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
bindView();//获取RecyclerView
initData();//初始化数据
linearLayoutManager = new LinearLayoutManager(this);//初始化布局管理器
recyclerView.setLayoutManager(linearLayoutManager);//设置布局管理器
recyclerView.setItemAnimator(new DefaultItemAnimator());//设置动画
recycleviewAdapter = new RecycleviewAdapter(mData);//初始化适配器
recyclerView.setAdapter(recycleviewAdapter);//设置适配器
}
private void bindView(){
recyclerView = findViewById(R.id.recycleview);
}
private void initData(){
mData = new ArrayList<>();
mData.add(new MyItem("未入库","单号:123456","2020.11.10","08:38"));
//...
}
}