Android:RecyclerView使用方法

3.18RecyclerView使用

    使用RecycleView需要先导入依赖,找到build.gradle文件,dependences修改。RecycleView在V7包下,导入和compileSdkVersion一致的版本。

示例:

implementation 'com.android.support:recyclerview-v7:29.0.0'

    在新版AndroidStudio中也可以通过下面语句导入,如果导入过后,layout文件中提示不出来,关闭项目后再打开。

示例:

implementation 'androidx.recyclerview:recyclerview:1.0.0'

示例:MainActivity中setRecyclerView方法,设置RecyclerView。

public class MainActivity extends AppCompatActivity {
    //上下文
    private Context mContext;
    private RecyclerView recyclerView;
    //按钮
    private Button button_add;
    private Button button_del;
    //显示list
    ArrayList arrayList;
    //RecycleViewAdpater
    RecyclerViewAdapter recyclerViewAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext=MainActivity.this;
        recyclerView=findViewById(R.id.recyclerview1);
        button_add=findViewById(R.id.btn_add);
        button_del=findViewById(R.id.btn_del);
        //设置RecyclerView
        setRecyclerView();

        //设置按钮点击事件
        button_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加Item
                recyclerViewAdapter.addItem("new Item",1);
            }
        });
        button_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除一个item
                recyclerViewAdapter.removeItem(1);
            }
        });
    }

    //设置recyclerview
    private void setRecyclerView(){
        //创建显示数据
        arrayList=new ArrayList<>();
        for(int i=0;i<10;i++){
            arrayList.add("Item"+i);
        }
        //创建适配adpter对象
        recyclerViewAdapter=new RecyclerViewAdapter(arrayList);
        //设置item点击事件
        recyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(mContext,"点击了"+position,Toast.LENGTH_LONG).show();
            }
        });
        //设置适配器Adpter
        recyclerView.setAdapter(recyclerViewAdapter);
        //创建自定义布局layoutManager
        RecyclerView.LayoutManager manager=new MyLayoutManager();
        //使用默认线性布局
        manager=new LinearLayoutManager(mContext);
        //使用网格布局,参数1 context:上下文;参数2 spanCount:网格列数
        // manager=new GridLayoutManager(mContext,3);
        //使用网格布局,参数3:网格布局水平或竖直方向;参数4 reverseLayout:是否反向布局
        //manager=new GridLayoutManager(mContext,3,GridLayoutManager.HO

你可能感兴趣的:(Android,android,RecyclerView)