RecyclerView的简单使用

前言

recyclerView可实现很多丰富的效果,本文主要实现带有分割线的列表,并实现监听对条目的删除。


源码在最后

一、设置监听

这里我们需要在适配器中定义一个接口OnItemClickListener和setOnItemClickListener()方法来同步监听:

 //定义接口并提供回调
    public interface OnItemClickListener{
        void onItemClick(View view,int position);
        //长点击监听
        void onItemLongClick(View view,int position);
    }
    //将activity的监听与当前监听进行同步
    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemClickListener = onItemClickListener;
    }

在RecyclerActivity中通过RecyclerAdapter调用setOnItemClickListener()方法并传入一个我们在RecyclerAdapter中定义的接口:

//对列表设置监听
  mAdapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(RecyclerActivity.this,"点击了"+(position+1)+"条",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(View view, int position) {
                new AlertDialog.Builder(RecyclerActivity.this)
                        .setTitle("确定要删除吗?")
                        .setNegativeButton("取消",null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mAdapter.removeData(position);
                            }
                        }).show();
            }
        });

`

一、全部代码

activity_recycler.xml:就是一个recyclerView控件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RecyclerActivity">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

activity的代码:

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class RecyclerActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
RecyclerAdapter mAdapter;
List<String> mList;
DividerItemDecoration mDivider;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler);
        mRecyclerView = findViewById(R.id.rv_recycler);
        mList = new ArrayList<>();
        //添加数据
        for (int i = 0; i < 15; i++) {
            //转int为string
            mList.add(String.valueOf(i));
        }
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));//默认是垂直排列的
//        如果想要设置为水平排列,则按如下代码
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
//        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
//        mRecyclerView.setLayoutManager(linearLayoutManager);
        //设置item增加和删除时的动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mAdapter = new RecyclerAdapter(mList,this);
        //添加分割线
        mDivider = new androidx.recyclerview.widget.DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        mRecyclerView.addItemDecoration(mDivider);
        //对列表中的条目设置监听
        mAdapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(RecyclerActivity.this,"点击了"+(position+1)+"条",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(View view, int position) {
                new AlertDialog.Builder(RecyclerActivity.this)
                        .setTitle("确定要删除吗?")
                        .setNegativeButton("取消",null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mAdapter.removeData(position);
                            }
                        }).show();
            }
        });
        //给列表设置适配器
        mRecyclerView.setAdapter(mAdapter);
    }
}

adapter的代码:在onCreateViewHolder中加载条目布局,在onBindViewHolder中将视图与数据进行绑定,removeData方法用来删除条目数据。

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder>  {
    private OnItemClickListener onItemClickListener;
    private List<String> mList;
    private Context mContext;

    public RecyclerAdapter(List<String> mList, Context mContext) {
        this.mList = mList;
        this.mContext = mContext;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, final int viewType) {
    //利用打气筒对象将layout_recycler_item.xml填充成view
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_recycler_item,parent,false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.textView.setText(mList.get(position));
        //对列表视图设置点击事件监听并回调给我们自定义的监听
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null){
                    //getAdapterPosition()获取点击了第几个条目
                    onItemClickListener.onItemClick(v, holder.getAdapterPosition() );
                }
            }
        });
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (onItemClickListener != null){
                    onItemClickListener.onItemLongClick(v, holder.getAdapterPosition());
                }
                return false;
            }
        });
    }

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


    static class ViewHolder extends RecyclerView.ViewHolder{
        TextView textView;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.tv_item);
        }
    }

    public void removeData(int position){
        mList.remove(position);//删除数据源中的数据
        notifyItemRemoved(position);//移除条目并刷新
    }

    //定义接口并提供回调
    public interface OnItemClickListener{
        void onItemClick(View view,int position);
        void onItemLongClick(View view,int position);
    }
    //将activity的监听与当前监听进行同步
    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemClickListener = onItemClickListener;
    }
}


layout_recycler_item布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:text="number"
        android:id="@+id/tv_item"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="50dp"/>
</LinearLayout>

最终效果图
RecyclerView的简单使用_第1张图片

总结

第一次写博客,不好的地方还请理解,大家一起互相学习。

你可能感兴趣的:(android,android,studio,java)