Mihir Patel Mihir Patel - 4 months ago 28
Android Question

How to receive callback from Activity class into ListView Adapter class in android?

I have Activity with a custom Listview and button. Now
I want to implement Activity button callback in adapter class.
How its possible in Android ?
Please give me suggestion.

Answer

FIRST SOLUTION OWN LISTENER

It should be done by Listeners, create Listener interface in Activity, next implement interface in Adapter class. Set Adapter object as listener of Activity and last thing run Listener methods when You want to do something in Adapter.

class Activity{

 private Listener listener;

 //your activity listener interface
 public interface Listener{

      onButtonClick();
 }


 private void setListener(Listener listener){

    this.listener=listener;
 }

 //example method
 private void youMethod(){

   YourAdapter adapter=new YourAdapter();//YourAdapter class implements Listener
   //here You say that adapter is You listener
   setListener(adapter);

   //bind button 
   Button button = (Button)findViewById(R.id.buttonName);
   button.setOnClickListener(new OnClickListener() {
     public void onClick(View v)
     {

        //run listener after button click
        buttonIsClicked();
        //or
        //listener.onButtonClick();
     } 
  });

 }

 private void buttonIsClicked(){
   //here use method
   listener.onButtonClick();
 }
}


//EXAMPLE ADAPTER
class YourAdapter implements Activity.Listener{

 //...adapter code

 void onButtonClick(){

   //your code on button click
 }
}

SECOND SOLUTION ADAPTER AS ONCLICKLISTENER

class Activity{


 //example method
 private void youMethod(){

   YourAdapter adapter=new YourAdapter();

   //bind button 
   Button button = (Button)findViewById(R.id.buttonName);
   //set adapter as onClickListener
   button.setOnClickListener(adapter);

 }

}


//EXAMPLE ADAPTER  
class YourAdapter implements OnClickLstener{

 //...adapter code

  public void onClick(View v)
  {

        //adpater code after click
  } 
}

THIRD SOLUTION - IT CAN BE DONE WITHOUT INTERFACE ( NOT GOOD PRACTICE )

Just add method to Your adapter and use it:

button.setOnClickListener(new OnClickListener() {
     public void onClick(View v)
     {

        //use adapter
        adapter.onButtonClick();
     } 
  });


//EXAMPLE ADAPTER WITHOUT INTERFACE
class YourAdapter{

 //...adapter code

 void onButtonClick(){

   //your code on button click
 }
}
Comments