RecyclerView使用指南

是用来替代ListView和Gallery的

可以实现列表和九宫格的横向和纵向的滑动以及瀑布流效果

要想使用就要添加v7包的支持

需要联合使用Adapter和ViewHolder和LayoutManager

纵向和横向滑动效果的实现




    


public class MainActivity extends AppCompatActivity {
    /**
     * rv相关联的类:
     * 1.布局管理器,用来设置rv的显示风格,如列表,网格,瀑布流,XXXLayoutManager
     * 2.适配器,Adapter
     * 3.ViewHolder
     */

    @BindView(R.id.rv)
    RecyclerView mRv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        //1.设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);//这个就是实现横向滑动
        mRv.setLayoutManager(linearLayoutManager);

        //2.设置适配器
        mRv.setAdapter(new MyRvAdapter());
    }

    private class MyRvAdapter extends RecyclerView.Adapter {
        //创建ViewHolder
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, parent, false);
            return new MyRvViewHolder(view);
        }

        //对ViewHolder里面的控件进行赋值
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            MyRvViewHolder myRvViewHolder = (MyRvViewHolder) holder;
            myRvViewHolder.setData(position);
        }

        //RV的条目数量
        @Override
        public int getItemCount() {
            return 50;
        }
    }

    private class MyRvViewHolder extends RecyclerView.ViewHolder {

        private TextView mTextView;
        private int position;

        public MyRvViewHolder(View itemView) {
            super(itemView);
            mTextView = itemView.findViewById(R.id.tv_test);
        }

        public void setData(int position) {
            this.position = position;
            mTextView.setText("哈哈哈哈哈" + position);
        }
    }
}


    
    


你可能感兴趣的:(RecyclerView使用指南)