Search code examples
javaandroidinterfaceadapterandroid-recyclerview

How can I pass data back to an adapter using an interface


I've tried to check on similar posts before asking but I haven't quite understood.

I have implemented a custom interface like below:

public interface OnChangeColor {
  void onColorChanged();
}

trying to set the color from an activity so that one of the recycler view item changes color:

class A extends AppCompatActivity {

 void passData(){
   OnChangeColor onChangeColor = this;
   onChangeColor.onColorChanged();
 }

and the implementation inside the adapter, of which it doesn't get called:

class MyAdapter … implements OnColorChanged{
   onColorChanged(){
      //Do something  
   }

how can I pass data back to the adapter using an interface?


Solution

  • You ned to set your implementation of interface in activity A.

    class A extends AppCompatActivity {
    private MyAdapter adapter = MyAdapter()
     ....
    void passData(){
       OnChangeColor onChangeColor = adapter;
       onChangeColor.onColorChanged();
     }
    }
    

    In that case you will be calling onColorChanged() on instance of your interface in MyAdapter

    But yeah... Why just not create method in adapter class and call it from activity. You don't need interface for this.