如何在 Fragment 和适配器之间创建接口? [英] How to create interface between Fragment and adapter?
问题描述
我有带有 ListView
的片段,比如 MyListFragment
和自定义的 CursorAdapter
.我正在此适配器中为列表行中的按钮设置 onClickListener
.
I have fragment with ListView
, say MyListFragment
, and custom CursorAdapter
.
I'm setting onClickListener
in this adapter for the button in the list row.
public class MyListAdapter extends CursorAdapter {
public interface AdapterInterface {
public void buttonPressed();
}
...
@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
...
holder.button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// some action
// need to notify MyListFragment
}
});
}
}
public MyListFragment extends Fragment implements AdapterInterface {
@Override
public void buttonPressed() {
// some action
}
}
我需要在按下按钮时通知片段.如何调用这个接口?
I need to notify fragment when the button is pressed. How to invoke this interface?
请帮忙.
推荐答案
创建一个新的构造函数和一个实例变量:
Make a new constructor and an instance variable:
AdapterInterface buttonListener;
public MyListAdapter (Context context, Cursor c, int flags, AdapterInterface buttonListener)
{
super(context,c,flags);
this.buttonListener = buttonListener;
}
创建适配器时,实例变量将被赋予适当的引用以保持.
When the Adapter is made, the instance variable will be given the proper reference to hold.
通过点击调用片段:
public void onClick(View v) {
buttonListener.buttonPressed();
}
在制作 Adapter
时,您还必须将 Fragment 传递给 Adapter.例如
When making the Adapter
, you will have to also pass your Fragment off to the Adapter. For example
MyListAdapter adapter = new MyListAdapter (getActivity(), myCursor, myFlags, this);
因为 this
将引用您的 Fragment,它现在是一个 AdapterInterface
.
since this
will refer to your Fragment, which is now an AdapterInterface
.
请记住,在 Fragment 的方向发生变化时,它很可能会被重新创建.如果您的 Adapter 没有重新创建,它可能会保留对不存在对象的引用,从而导致错误.
Keep in mind that on orientation of the Fragment changes, it will most likely be recreated. If your Adapter isn't recreated, it can potentially keep a reference to a nonexistent object, causing errors.
这篇关于如何在 Fragment 和适配器之间创建接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!