Adapter和Activity之间实现接口回调

在Adapter里设置一个内部接口


    CallbackInterface callbackInterface;

    interface CallbackInterface{

        void callbackMethod(int position);
    }

点击Adapter某一个的item时,调用接口方法

  item1_linear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callbackInterface.callbackMethod(position);
            }
        });

在Activity中实现接口

 adapter.callbackInterface = new MyAdapter.CallbackInterface() {
            @Override
            public void callbackMethod(int position) {

                main_tv.setText("点击了第:"+position+"个item");

            }
        };

整体代码

activity_main.xml

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

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv"
            android:layout_weight="9"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <TextView
            android:id="@+id/main_tv"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:gravity="center"
            android:layout_gravity="center"
            android:layout_marginBottom="20dp"
            android:text="记录点击事件" />


</LinearLayout>

item1.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"
    android:id="@+id/item1_linear"
    android:layout_margin="5dp"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:background="#22000000"
    android:padding="5dp"
    android:layout_height="wrap_content">


    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:textSize="12dp"
        android:text="账号" />

    <TextView
        android:id="@+id/tv_name"
        android:text="消息"
        android:layout_margin="3dp"
        android:paddingRight="2dp"
        android:paddingLeft="2dp"
        android:padding="3dp"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java


import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private RecyclerView rv;
    private ArrayList<UserInfo> list;
    private MyAdapter adapter;
    private TextView main_tv;

    private LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去掉顶部标题
        getSupportActionBar().hide();
        setContentView(R.layout.activity_main);

        list = new ArrayList<>();
        rv = (RecyclerView) findViewById(R.id.rv);
        main_tv = (TextView)findViewById(R.id.main_tv);
        adapter = new MyAdapter(this);

        initData();

        adapter.callbackInterface = new MyAdapter.CallbackInterface() {
            @Override
            public void callbackMethod(int position) {

                main_tv.setText("点击了第:"+position+"个item");
            }
        };

        // 向适配器set数据
        adapter.setData(list);
        rv.setAdapter(adapter);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rv.setLayoutManager(manager);


        }


    // 数据初始化
    private void initData(){

        for(int i = 0; i<10; i++){
            UserInfo info = new UserInfo("123","消息"+(i+1));
            list.add(info);
        }

    }

}



MyAdapter.java


import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter {
    private Context context;
    private ArrayList<UserInfo> data;

    public MyAdapter(Context context) {
        this.context = context;
        data = new ArrayList<>();
    }


    public void setData(ArrayList<UserInfo> data) {

        this.data = data;

        // 刷新
        notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(int position) {

        return 1;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder = null;

        View view = LayoutInflater.from(context).inflate(R.layout.item1,parent,false);
        holder = new OneViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        OneViewHolder oneViewHolder = (OneViewHolder) holder;

        oneViewHolder.name1.setText((String)data.get(position).getData());

        oneViewHolder.item1_linear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callbackInterface.callbackMethod(position);
            }
        });

    }


    @Override
    public int getItemCount() {
        return  data != null && data.size() > 0 ? data.size() : 0;
    }

    class OneViewHolder extends RecyclerView.ViewHolder{
        private TextView tv1;
        private TextView name1;
        private LinearLayout item1_linear;
        public OneViewHolder(View itemView) {
            super(itemView);
            tv1 = (TextView) itemView.findViewById(R.id.tv1);
            name1 = (TextView) itemView.findViewById(R.id.tv_name);

            item1_linear = (LinearLayout) itemView.findViewById(R.id.item1_linear);

        }
    }


    CallbackInterface callbackInterface;

    /**
     * 回调接口
     */
    interface CallbackInterface{

        void callbackMethod(int position);
    }


}

实体类 UserInfo.java


import java.io.Serializable;

public class UserInfo implements Serializable {

    /**
     * 账号
     */
    private String zhanghao;

    /**
     * 内容
     */
    private String data;



    public UserInfo(String zhanghao, String data){
         this.zhanghao = zhanghao;

         this.data = data;

    }


    public String getZhanghao() {
        return zhanghao;
    }

    public void setZhanghao(String zhanghao) {
        this.zhanghao = zhanghao;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                ", zhanghao='" + zhanghao + '\'' +
                ", data='" + data + '\'' +
                '}';
    }
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是 Kotlin 中使用 RecyclerView 实现左滑删除 item 的代码实现: 1. 在 RecyclerView 的 item 布局文件中添加一个滑动删除的按钮,例如使用 ImageButton 实现: ```xml <ImageButton android:id="@+id/btn_delete" android:layout_width="wrap_content" android:layout_height="match_parent" android:background="@color/colorAccent" android:padding="16dp" android:src="@drawable/ic_delete" /> ``` 2. 在 RecyclerView 的 ViewHolder 中设置按钮的点击事件,并定义一个接口用于回调删除事件: ```kotlin class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(item: MyItem, listener: OnItemClickListener) = with(itemView) { // 绑定 item 数据 // ... // 设置删除按钮点击事件 btn_delete.setOnClickListener { listener.onDeleteClick(adapterPosition) } } } interface OnItemClickListener { fun onDeleteClick(position: Int) } ``` 3. 在 RecyclerView 的 Adapter实现删除事件的回调: ```kotlin class MyAdapter(private val items: List<MyItem>, private val listener: OnItemClickListener) : RecyclerView.Adapter<MyViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_my, parent, false) return MyViewHolder(view) } override fun getItemCount() = items.size override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.bind(items[position], listener) } fun deleteItem(position: Int) { // 删除数据 // ... // 刷新界面 notifyItemRemoved(position) } } ``` 4. 在 Activity 或 Fragment 中实现删除事件的具体操作: ```kotlin class MyActivity : AppCompatActivity(), OnItemClickListener { private lateinit var adapter: MyAdapter private lateinit var recyclerView: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_my) // 初始化 RecyclerView 和 Adapter recyclerView = findViewById(R.id.recycler_view) adapter = MyAdapter(getMyItems(), this) recyclerView.adapter = adapter // 设置 RecyclerView 的左滑删除功能 val swipeHandler = object : SwipeToDeleteCallback(this) { override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val position = viewHolder.adapterPosition adapter.deleteItem(position) } } val itemTouchHelper = ItemTouchHelper(swipeHandler) itemTouchHelper.attachToRecyclerView(recyclerView) } override fun onDeleteClick(position: Int) { // 在这里实现删除 item 的具体操作,例如弹出确认对话框等 // ... // 删除 item adapter.deleteItem(position) } } ``` 以上就是使用 Kotlin 实现 RecyclerView 左滑删除 item 的代码实现。注意,其中使用了 SwipeToDeleteCallback 类来实现左滑删除的功能,这个类需要自己实现

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Android 《开发》

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值