RecyclerView 是比較先進而靈活的 ListView
RecyclerView 除了要使用 RecyclerView.Adapter 之外還必須指定一個 RecyclerView.LayoutManager
內建的 LayoutManager 有以下三種:
LinearLayoutManager (垂直或水平捲動的 List)
GridLayoutManager
StaggeredGridLayoutManager (交錯的 Grid)
另外 RecyclerView 對 item 的增加與移除有預設動畫
要自訂動畫的話必須繼承自 RecyclerView.ItemAnimator
再透過 RecyclerView.setItemAnimator() 指定
RecyclerView 在 layout xml 是長這樣
接下來看看 code 要怎麼用
public class MyActivity extends Activity { private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_activity); mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); //如果內容的改變不會改變 RecyclerView 的 layout size, 這可以增進效能 mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); // specify an adapter (see also next example) mAdapter = new MyAdapter(myDataset); mRecyclerView.setAdapter(mAdapter); } ...省略 }
繼承 RecyclerView.Adapter 的實作範例
public class MyAdapter extends RecyclerView.Adapter{ private String[] mDataset; // 繼承 RecyclerView.ViewHolder 的 ViewHolder public static class ViewHolder extends RecyclerView.ViewHolder { // each data item is just a string in this case public TextView mTextView; public ViewHolder(TextView v) { super(v); mTextView = v; } } // 透過 constructor 傳入 dataset public MyAdapter(String[] myDataset) { mDataset = myDataset; } // 在 onCreateViewHolder 將 item view 給 inflate @Override public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.my_text_view, parent, false); // 調整 view 的 size, margins, paddings 及其他 layout parameters ...省略 ViewHolder vh = new ViewHolder(v); return vh; } // 在 onBindViewHolder 將 item view 的內容(依照 position )做更換 @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.mTextView.setText(mDataset[position]); } @Override public int getItemCount() { return mDataset.length; } }
相關資料:
Creating Lists and Cards
Android develop 官方範例 - RecyclerView
沒有留言:
張貼留言