1. 在gradle.build的dependencies中添加RecyclerView需要的包
compile ‘com.android.support:cardview-v7:23.4.0‘compile ‘com.android.support:recyclerview-v7:23.4.0‘ 添加完后记得要Sync Gradle
2. 在布局文件中添加控件RecyclerView.
<android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="wrap_content"> </android.support.v7.widget.RecyclerView>
3.在Activity中找到RecyclerView并设置LayoutManager和Adapter
RecyclerView rv;
NewsAdapter adapter;
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rv = (RecyclerView) findViewById(R.id.rv); rv.setLayoutManager(new LinearLayoutManager(this)); rv.setAdapter(adapter); }
4. 写Adapter
class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.VH> { String[] data = {"a","b","c","d","e"}; //创建ViewHoler @Override public VH onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item,parent,false); VH vh = new VH(view); return vh; } //数据绑定 @Override public void onBindViewHolder(VH holder, int position) { holder.title.setText(data[position]); } @Override public int getItemCount() { return data.length; } //内部类VH 保存所有view class VH extends RecyclerView.ViewHolder { public TextView title; public VH(View itemView) { super(itemView); title = (TextView)itemView.findViewById(R.id.title); } } }
时间: 2024-10-10 04:29:42