美文网首页
Component-RecyclerView

Component-RecyclerView

作者: 阳光丶不错 | 来源:发表于2018-05-18 17:27 被阅读0次

    关键点:

    • LayoutManager: LinearLayoutManager / GridLayoutManager
    • RecyclerView.ViewHolder
    • RecyclerView.adapter

    使用步骤:

    添加支持库

    dependencies {
        implementation 'com.android.support:recyclerview-v7:27.1.1'
    }
    

    在Layout中添加RecyclerView:

    <android.support.v7.widget.RecyclerView/>
    

    添加代码:

    • 构造RecyclerView.ViewHolder & RecyclerView.Adapter
    public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
        private String[] mDataset;
    
        public MyAdapter(String[] myDataset) {
            mDataset = myDataset;
        }
        //先继承RecyclerView.ViewHolder构造ViewHolder内部类
        //再使用泛型RecyclerView.Adapter<VH extends ViewHolder>
        @Override
        public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                       int viewType) {
            TextView tv = (TextView) LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.my_text_view, parent, false);
            ViewHolder vh = new ViewHolder(tv);
            return vh;
        }
    
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            holder.mTextView.setText(mDataset[position]);
        }
    
        @Override
        public int getItemCount() {
            return mDataset.length;
        }
    
        public static class ViewHolder extends RecyclerView.ViewHolder {
            public TextView mTextView;
            public ViewHolder(TextView v) {
                super(v);
                mTextView = v;
            }
        }
    }
    
    • 属性设置部分
    RecyclerView  mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
    RecyclerView.Adapter mAdapter = new RecyclerViewAdapter(mDataSet);
    
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setAdapter(mAdapter);
    

    有关方法:

    //如果RecyclerView的内容改变但是Size不变的话使用该方法可以提高性能。
    setHasFixedSize()
    

    相关文章

      网友评论

          本文标题:Component-RecyclerView

          本文链接:https://www.haomeiwen.com/subject/trngdftx.html