如何片段和适配器之间建立接口? [英] How to create interface between Fragment and adapter?

查看:118
本文介绍了如何片段和适配器之间建立接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有片段,的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
    }
}

我需要通知的片段时,按钮pssed $ P $。如何调用该接口?

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();
}

在制作适配器,你将不得不也通过你的碎片关闭的适配器。例如

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);

因为将参考您的片段,也就是现在的 AdapterInterface

since this will refer to your Fragment, which is now an AdapterInterface.

请记住,在该片段的变化方向,这将最有可能被重新创建。如果您的适配器是不是重新创建,它可能会保持一个引用不存在的对象,导致错误。

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.

这篇关于如何片段和适配器之间建立接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆