Adapter中调用Activity中的方法

Call Activity method from adapter

up vote 7 down vote favorite
9

Is it possible to call mathod 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 current 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 ?

share | improve this question
 
 
you cannot call activity.this in some other class unless it is a inner class to that activity. follow @Eldhose M Babu solution for your case –   Archie.bpgc  Aug 27 '12 at 13:03 

2 Answers

active oldest votes
up vote 26 down vote accepted

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) { ((YourActivityName)mContext).yourDesiredMethod(); } });

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

share | improve this answer
 
 
Yes I can! ...now :D thx –   user1602687  Aug 27 '12 at 13:22
 
Awesome man!! Thanks a lot!!!! :) –   nithinreddy  Mar 7 '13 at 12:08
 
this not working when i call from the outer class adapter –   Issac Balaji  Sep 24 at 8:26
 
I have similar problem. in my case, it is Fragment what should i use instead of((YourActivityName)mContext).yourDesiredMethod(); –   Jeeten Parmar  Oct 15 at 9:10
up vote 29 down vote

You can do it this way:

Declare interface:

public interface MyInterface{ public void foo(); }

Let your Activity imlement it:

 public class MyActivity extends Activity implements MyInterface{ public void foo(){ //do stuff } }

Then pass your activity to ListAdater:

public MyAdapter extends BaseAdater{ private MyInterface listener; public MyAdapter(MyInterface listener){ this.listener = listener; } }

And somewhere in adapter, when you need to call that Activity method:

listener.foo();
share | improve this answer
 
4  
This is best practice!! –   Lisa Anne  Mar 3 '13 at 16:49
1  
Like this one better. –   goodm  Mar 18 '13 at 12:12
1  
I first thought of the method above as you would with fragments but this is the best solution! –   brux  Aug 2 '13 at 0:55
1  
thank you , best practice! –   daimajia  Sep 9 '13 at 7:51 

总结:(1)第一种方案是将activity传递过去;
   (2)第二中方案是写一个接口,acitivity中实现这个接口,传递给adapter进行调用。

你可能感兴趣的:(Adapter中调用Activity中的方法)