从(列表)适配器回调到活动 [英] Callback from (List)Adapter to Activity
问题描述
我有一个带有ListView的Actvivity,我设置了一个适配器
I have an Actvivity with a ListView, I set an adapter
MyAdapter extends BaseAdapter
该适配器具有回调接口
OnPdfClickedListener callback;
public interface OnPdfClickedListener {
public void onPdfClicked();
}
和活动"中
MyActvivity implements MyAdapter.OnPdfClickedListener
和
@Override
public void onPdfClicked() {
Log.d("TEST", "PDF CLICKED in ACTVIIVTY");
}
这与此处所述相同,喜欢碎片的魅力.从适配器尝试相同操作时,回调对象为null.
This is pretty much the same as described here, which works like charm for fragments. When trying the same from the adapter the callback object is null.
我也尝试实例化
OnPdfClickedListener callback = new OnPdfClickedListener() {
@Override
public void onPdfClicked() {
// TODO Auto-generated method stub
}
};
那时我没有错误,但是从未调用Activity中的相应方法.
I have no errors then but the respective method in the Activity is never called.
我的问题是1.为什么在片段中使用回调对象时,它为什么不为空,却从未实例化
My question is 1. why isn't the callback object null when used in a fragment, it's never instantiated
和2.如何从适配器回调到活动?
and 2. how can I callback to an Activity from an adapter?
推荐答案
- 为什么在片段中使用回调对象时,它不为null,所以永远不会实例化
您创建的 callback
变量很可能未将您的 Activity
注册为侦听器(与 Activity
) OnPdfClickedListener
的实例,并且(可能)在事件发生时使用了该实例.
Your Activity
most likely isn't registered as a listener, with the callback
variable you created(which has nothing to do with the Activity
) an instance of OnPdfClickedListener
and (probably) used that when the event happened.
如何从适配器回调到活动?
how can I callback to an Activity from an adapter?
将对 Activity
的引用传递到您的 MyAdapter
类,将其强制转换为 OnPdfClickedListener
,然后使用该调用来调用 onPdfClicked
而不是当前的 callback
变量.
Pass a reference to the Activity
to your MyAdapter
class, cast it to OnPdfClickedListener
and use that to call onPdfClicked
instead of the current callback
variable.
这篇关于从(列表)适配器回调到活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!