我有带有 ListView
的 fragment ,比如 MyListFragment
和自定义 CursorAdapter
。
我在此适配器中为列表行中的按钮设置 onClickListener
。
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
}
}
我需要在按下按钮时通知 fragment 。如何调用这个接口(interface)?
请帮忙。
最佳答案
创建一个新的构造函数和一个实例变量:
AdapterInterface buttonListener;
public MyListAdapter (Context context, Cursor c, int flags, AdapterInterface buttonListener)
{
super(context,c,flags);
this.buttonListener = buttonListener;
}
当适配器被制作时,实例变量将被赋予正确的引用来保持。
从点击调用 fragment :
public void onClick(View v) {
buttonListener.buttonPressed();
}
在制作 Adapter
时,您还必须将 Fragment 传递给 Adapter。例如
MyListAdapter adapter = new MyListAdapter (getActivity(), myCursor, myFlags, this);
因为 this
将引用您的 Fragment,它现在是一个 AdapterInterface
。
请记住,在 Fragment 的方向发生变化时,它很可能会被重新创建。如果您的适配器没有重新创建,它可能会保留对不存在的对象的引用,从而导致错误。
关于java - 如何在 Fragment 和适配器之间创建接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15444375/