Android 筆記 - RecyclerView (取代 ListView)

 當有條列式的多行要顯示時可用,要顯示成網格也行


首先要定義 Adapter

內容大致如下

class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tv;
public ViewHolder(@NonNull View itemView) {
// 在這裡find其他物件
super(itemView);
tv = itemView.findViewById(R.id.tv);
}
}

private String[] name = { "111", "222", "333" };
MyAdapter(Context context) {
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.
from(parent.getContext()).inflate(R.layout.你的內容xml, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // 在這裡變更物件值
holder.
tv.setText(name[position]);
}

@Override
public int getItemCount() {
return name.length;
}
}


主要的 RecycleView 部份


listAdapter = new MultiLedgerAdapter();
rv_list = activity.findViewById(R.id.rv_list);
rv_list.setLayoutManager(new LinearLayoutManager(context));
rv_list.setAdapter(listAdapter);

要注意的是,除了 setAdapter 之外,還要指定 setLayoutManager ,不然會顯示不出來哦~


設定佈局 setLayoutManager 選擇

有三種可選擇

1. LinearLayoutManager - 線性佈局管理器
2. StaggeredGridLayoutManager - 錯列網格佈局管理器
3. GridLayoutManager - 網格佈局管理器

LinearLayoutManager 語法及效果圖


rv_list.setLayoutManager(new LinearLayoutManager (context));

rv_list.setLayoutManager(new LinearLayoutManager (context, LinearLayoutManager.VERTICAL, false));


rv_list.setLayoutManager(new LinearLayoutManager (context, LinearLayoutManager.VERTICAL, true));


rv_list.setLayoutManager(new LinearLayoutManager (context, LinearLayoutManager.HORIZONTAL, false));


rv_list.setLayoutManager(new LinearLayoutManager (context, LinearLayoutManager.HORIZONTAL, true));


StaggeredGridLayoutManager 語法及效果圖


rv_list.setLayoutManager(new StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL));


rv_list.setLayoutManager(new StaggeredGridLayoutManager(3, LinearLayoutManager.HORIZONTAL));


GridLayoutManager 語法及效果圖


rv_list.setLayoutManager(new GridLayoutManager(context, 3, LinearLayoutManager.VERTICAL, false));


rv_list.setLayoutManager(new GridLayoutManager(context, 3, LinearLayoutManager.VERTICAL, true));


rv_list.setLayoutManager(new GridLayoutManager(context, 3, LinearLayoutManager.HORIZONTAL, false));


rv_list.setLayoutManager(new GridLayoutManager(context, 3, LinearLayoutManager.HORIZONTAL, true));





沒有留言:

張貼留言