从接口调用活动的方法 [英] Call Activity method from adapter
问题描述
是否有可能调用在活动
从 ListAdapter
?
(我想在列表的
一行按钮
键,单击此按钮时,它应该执行方法,那就是在当前的活动定义的。我试着设置 onClickListener
在我的 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...)
当我用 Activity.this.method()
我收到以下错误:
when I used Activity.this.method()
I get the following error:
No enclosing instance of the type Activity is accessible in scope
你知道吗?
推荐答案
当然可以。
在适配器:
添加一个新的领域: 民营背景mContext;
Add a new Field : private Context mContext;
在适配器构造函数中添加以下code:
In the adapter Constructor add the following code :
public AdapterName(......,Context context){
...your code.
this.mContext=context;
}
在适配器的getView(...):
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();
}
}
});
替换,你看你的code自己的类的名字,你的活动等。
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 :
创建一个接口
public interface IMethodCaller{
void yourDesiredMethod();
}
您需要有这个方法调用的功能实现此接口的活动。
Implement this interface in activities you require to have this method calling functionality.
然后在适配器getView()调用,如:
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();
}
}
});
您完成。如果你需要使用这个适配器的活动,它不需要这种调用机制,code将不执行(如果检查失败)
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).
这篇关于从接口调用活动的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!