How to call a function of fragment from custom adapter

Mukesh Mishra picture Mukesh Mishra · Dec 23, 2016 · Viewed 11.6k times · Source

I have created a function in fragment. And I want to call that function when a button clicks which is in custom adapter but I am not able to call function of fragment from custom adapter.

My code for adapter is to click on a button and call fragment's function

                 viewHolder.accept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeListItem(viewHolder.order_card_layout, position);

                android.support.v4.app.Fragment newFragment = new NewPageActivity();
                android.support.v4.app.FragmentTransaction ft = ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction();

                 ft.sendorder(data.getorder_id());
                ft.add(R.id.framelay, newFragment).commit();


            }
        });

My function that is in fragment

    public class NewPageActivity extends Fragment{
        public void SendOrder( String OrderId)
{

    final String serverid = sp.getString("serverid", "null");
    Log.e("TAG", "SendOrder: "+serverid +OrderId );
    new SendOrder().execute(new Config().addNewOrder, serverid, OrderId);
}
      }

Answer

sohan shetty picture sohan shetty · Dec 23, 2016

Create an Interface Class in adapter and implement in your fragment class like below

Inside Adapter class

         public Interface CallBack{
         void yourMethodName();

         }

Now in fragment class implement your interface method like below

public class YourFragment implements CallBack{
     ...........
     @Override
     public void yourMethodName(){
      //"here call your fragment method or do any bussiness logic 
      }    
  }

Finally you should call your interface method in your adapter onclick listener like below before that pass your interface instance to your adapter constructor

public class YourAdapterClass extends BaseAdapter {
  private CallBack mCallBack;
   public YourAdapterClass (CallBack callback){
    mCallBack = callback;
      }
    }

Then inside your onClickListener call your interface method like this

    @Override
        public void onClick(View v) {
           mCallBack.yourMethodName();


        }
    });

Done