简体   繁体   English

android:如何在回收器视图和适配器clss之间建立接口

[英]android: how to make interface between recycler view and adapter clss

I have a recyclerview which has Switch Button on each item and I want to add switch.setOnCheckedChangeListener for items. 我有一个recyclerview ,每个项目都有Switch Button,我想为项目添加switch.setOnCheckedChangeListener how can I make an interface between adapter class and the recyclerview host activity?? 如何在适配器类和recyclerview主机活动之间建立接口?

First you will create an interface class 首先,您将创建一个接口类

public interface ExampleInterface {
    void udpateData(String data);
}

The interface will be defined with name and parameters that you want 将使用您需要的名称和参数定义接口

Second in the activity or fragment having RecycleView, you need implement this interface. 在具有RecycleView的活动或片段中,您需要实现此接口。

Third, when you call the your adapter please pass this interface to your adapter. 第三,当您调用适配器时,请将此interface传递给适配器。 Each time your Switch Button change status, interface will call updateData method to update data 每次切换按钮更改状态时, interface都会调用updateData方法来更新数据

Good luck 祝好运

In your host activity write a method to handle switch button changed, say 在你的主机活动中写一个方法来处理切换按钮的变化,比方说

private void switchButtonChanged()

pass the host activity when you create the adapter, for example 例如,在创建适配器时传递主机活动

Adapter adapter = new Adapter(getActivity())

under your onCheckedChangedListener() in adapter, fire hostActivity.switchButtonChanged() 在适配器中的onCheckedChangedListener()下,触发hostActivity.switchButtonChanged()

There is a simple way to do it. 有一种简单的方法可以做到这一点。 interface. 接口。

public class YourAdapter extends YourAdapterExtends {
private AdapterInteractionListener adapterInteractionListener;
... // your adapter codes
public YourAdapter(AdapterInteractionListener adapterInteractionListener){
this.adapterInteractionListener = adapterInteractionListener;
}

//call where you call switch.setOnCheckedChangeListener method
switch. setOnCheckedChangeListener{
adapterInteractionListener.onSwitched;
}


//here your interaction interface.

    public interface AdapterInteractionListener{
        void onSwitched();
    }
}

And your host activity 和你的主持人活动

public class YourActivity extends YourExtends impelements YourAdapter.AdapterInteractionListener {
...//your activity codes
@Override
onSwitched{
//here your switch listener triggered here
}

}

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM