简体   繁体   中英

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. how can I make an interface between adapter class and the recyclerview host activity??

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.

Third, when you call the your adapter please pass this interface to your adapter. Each time your Switch Button change status, interface will call updateData method to update data

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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