说来惭愧,最近才发现这个组件,直接看代码吧.
1 2 3 4 5 6 7 8 9 10 <FrameLayout xmlns:android ="http://schemas.android.com/apk/res/android" android:layout_width ="match_parent" android:layout_height ="match_parent" > <android.support.v7.widget.RecyclerView android:id ="@+id/recyclerView" android:layout_width ="match_parent" android:layout_height ="match_parent" /> </FrameLayout >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 private RecyclerView recyclerView = null ; @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_auto_hide_tool_bar); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this ); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); linearLayoutManager.scrollToPosition(0 ); List<DataModel> list = new ArrayList<DataModel>(); for (int i = 0 ; i < 20 ; i++) { list.add(new DataModel("name" +i, "address" +i) ); } recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(new MyRecycleeAdapter(list)); }
实现 RecyclerView.Adapter 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 public ListItemViewHolder onCreateViewHolder (ViewGroup viewGroup, int i) ;public void onBindViewHolder (ListItemViewHolder listItemViewHolder, int i) ;public int getItemCount () ;public class MyRecycleeAdapter extends RecyclerView .Adapter <MyRecycleeAdapter .ListItemViewHolder > { private List<DataModel> list; public MyRecycleeAdapter (List<DataModel> list) { if (list == null ) { throw new IllegalArgumentException("list 不能为 null" ); } this .list = list; } @Override public ListItemViewHolder onCreateViewHolder (ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()) .inflate(R.layout.list_item, viewGroup, false ); return new ListItemViewHolder(view); } @Override public void onBindViewHolder (ListItemViewHolder listItemViewHolder, int i) { DataModel dataModel = list.get(i); listItemViewHolder.name.setText(dataModel.getName()); listItemViewHolder.address.setText(dataModel.getAddress()); } @Override public int getItemCount () { return list.size(); } public static final class ListItemViewHolder extends RecyclerView .ViewHolder { TextView name; TextView address; ListItemViewHolder(View itemView) { super (itemView); name = (TextView) itemView.findViewById(R.id.name); address = (TextView) itemView.findViewById(R.id.address); } } }
以上 就可以跑一个最简单的list了
熟悉 ListView 用法的话使用 RecyclerView 几乎没有难度
参考文章: