Fork me on GitHub

Android Studio教程11-RecycleView的使用

1. RecyclerView

1.1. Add support library

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

1.2. 将RecyclerView添加到布局

此文件命名为:activity_recycle_demo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".RecycleDemoActivity">

    <LinearLayout
        android:id="@+id/layout01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >

        <Button
            android:id="@+id/linearLayout_recycle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="线性布局"/>

        <Button
            android:id="@+id/grid_recycle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="网格布局"/>

        <Button
            android:id="@+id/staggeredLayout_recycle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="瀑布布局"/>

    </LinearLayout>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

</LinearLayout>

1.3. 主actiivty中如何调用recycleview对象

RecycleDemoActivity.java

package com.haoch95.fristapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class RecycleDemoActivity extends AppCompatActivity {

    private Button linearBT, gridBT, starBT;

    private RecyclerView mRecyclerView;
    private RecycleAdapter mMyAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<String> list;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycle_demo);

        linearBT = (Button)findViewById(R.id.linearLayout_recycle);
        gridBT = (Button)findViewById(R.id.grid_recycle);
        starBT = (Button)findViewById(R.id.staggeredLayout_recycle);
        // RecyclerView的三部曲 01: 获取RecyclerView对象
        mRecyclerView = (RecyclerView)findViewById(R.id.my_recycler_view);

        initData();

        linearBT.setOnClickListener(new ButtonClicked());
        gridBT.setOnClickListener(new ButtonClicked());
        starBT.setOnClickListener(new ButtonClicked());




//        // 添加水平分割线
//        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));

    }

    private void initData() {
        list = new ArrayList<>();
        for (int i=0;i<20;i++){
            list.add("Item" + i);
        }
    }

    class ButtonClicked implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.linearLayout_recycle:
                    mLayoutManager = new LinearLayoutManager(getApplicationContext());
                    break;
                case R.id.grid_recycle:
                    mLayoutManager = new GridLayoutManager(getApplicationContext(),4);
                    break;
                case R.id.staggeredLayout_recycle:
                    //如果传入 StaggeredGridLayoutManager.VERTICAL则该布局支持纵向滑动,那么前面的 4 则指的是 4列。
                    //如果传入 StaggeredGridLayoutManager.HORIZONTAL,则该布局支持横向滑动,那么前面的4 则指的是 4行
                    mLayoutManager = new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL);
                    break;
                default:
                    mLayoutManager = new LinearLayoutManager(getApplicationContext());
                    break;
            }
            //RecyclerView的三部曲 02:设置布局管理器
            mRecyclerView.setLayoutManager(mLayoutManager);
            mRecyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(),DividerItemDecoration.VERTICAL));
            // RecyclerView的三部曲 03: 添加适配器,适配器需要重写
            mMyAdapter = new RecycleAdapter(list, getApplicationContext());
            mRecyclerView.setAdapter(mMyAdapter);
            //设置Item增加、移除动画
            mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add:
                mMyAdapter.addData(1);
                break;
            case R.id.delete:
                mMyAdapter.removeData(1);
                break;
        }
        return true;
    }
}

1.4. 重写定义Adapter

RecycleAdapter


package com.haoch95.fristapp;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;
import java.util.Random;

public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> {

    private List<String> mList;
    private Context context;

    public RecycleAdapter(List<String> list, Context context){
        this.mList = list;
        this.context = context;
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }


    public class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView mView;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            mView = itemView.findViewById(R.id.text_view);
        }
    }

    //创建ViewHolder
    //onCreateViewHolder方法创建一个viewHolder,viewholder可以理解为一条数据的展示布局,这里我们自定义类LinearViewHolder创建一个只有TextView的item
    //这里我们需要创建每条布局使用的layout:recycle_item
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new MyViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycle_item, viewGroup, false));
    }


    //填充视图
    //onBindViewHolder方法为item的UI绑定展示数据
    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
        holder.mView.setText(mList.get(position));

        holder.itemView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                Toast.makeText(context, "点击子项"+position, Toast.LENGTH_SHORT).show();
            }
        });

    }

    public void addData(int position) {
        mList.add(position, "Insert One");
        notifyItemInserted(position);
    }

    public void removeData(int position) {
        mList.remove(position);
        notifyItemRemoved(position);
    }

    public void clearALL(){
        mList.clear();
        notifyDataSetChanged();
    }


}

2. 实例

本节中的所有代码已上传到:https://github.com/haochen95

posted @ 2019-01-21 20:24  Bricker666  阅读(1882)  评论(0编辑  收藏  举报