RecyclerView對我來說可以說是進階的Listview,不過它的功能比Listview更強大、更有彈性,程式碼也相對複雜不少,我在學習RecycleView的路上撞了不少牆,但現在我要用我的理解來跟你們介紹一下,這個看似複雜不過很實用的進階元件喔。
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="horizontal">
<TextView
android:id="@+id/fileTitle"
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="5dp"
android:gravity="center_vertical|left" ></TextView>
</LinearLayout>
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
ArrayList<String> ItemList;
//帶入ArrayList作為資料
public MyAdapter(ArrayList<String> itemList) {
this.ItemList = itemList;
}
@Override
//創建一個新的viewholder
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//負責找尋res/layout 下的佈局檔,功能類似findViewById()。
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_content, parent, false); //載入layout
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
//將正確的viewholder連接到正確的positon
holder.fileTitle.setText(ItemList.get(position));
//滑動畫面時,將資料位置綁至新的欄位,用新數據將之取代(RecyclerView特色)
}
//RecyclerView長度
@Override
public int getItemCount() {
return ItemList.size();
} //回傳titlelist總共有幾筆資料
class ViewHolder extends RecyclerView.ViewHolder { //綁定recycle的套件
public TextView fileTitle;
public ViewHolder(View holder) {
super(holder);
//綁定元件ID
fileTitle = (TextView) holder.findViewById(R.id.fileTitle);
}
}
}
public class MainActivity extends AppCompatActivity {
MyAdapter adapter;
RecyclerView recyclerView;
ArrayList<String> titleList = new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
//給titleList資料
for(int i = 0;i<20;i++){
titleList.add("項目"+i);
}
recyclerView.setLayoutManager(new LinearLayoutManager(this)); //垂直向下排列
recyclerView.addItemDecoration(new DividerItemDecoration(this, //分隔線
DividerItemDecoration.VERTICAL));
//將串列titlelist傳入MyAdapter,最後由recyclerView取用
adapter = new MyAdapter(titleList);
recyclerView.setAdapter(adapter);
}
}
其中特別要講的是
recyclerView.setLayoutManager(new LinearLayoutManager(this));
今天RecyclerView就講到這邊,謝謝大家~