androidlistadapteraddressing

Call Activity method from adapter


Is it possible to call method that is defined in Activity from ListAdapter?

(I want to make a Button in list's row and when this button is clicked, it should perform the method, that is defined in corresponding Activity. I tried to set onClickListener in my ListAdapter but I don't know how to call this method, what's its path...)

when I used Activity.this.method() I get the following error:

No enclosing instance of the type Activity is accessible in scope

Any Idea ?


Solution

  • Yes you can.

    In the adapter Add a new Field :

    private Context mContext;
    

    In the adapter Constructor add the following code :

    public AdapterName(......, Context context) {
      //your code.
      this.mContext = context;
    }
    

    In the getView(...) of Adapter:

    Button btn = (Button) convertView.findViewById(yourButtonId);
    btn.setOnClickListener(new Button.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (mContext instanceof YourActivityName) {
          ((YourActivityName)mContext).yourDesiredMethod();
        }
      }
    });
    

    replace with your own class names where you see your code, your activity etc.

    If you need to use this same adapter for more than one activity then :

    Create an Interface

    public interface IMethodCaller {
        void yourDesiredMethod();
    }
    

    Implement this interface in activities you require to have this method calling functionality.

    Then in Adapter getView(), call like:

    Button btn = (Button) convertView.findViewById(yourButtonId);
    btn.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mContext instanceof IMethodCaller) {
                ((IMethodCaller) mContext).yourDesiredMethod();
            }
        }
    });
    

    You are done. If you need to use this adapter for activities which does not require this calling mechanism, the code will not execute (If check fails).