【问题标题】:Where is the correct place to assign an interface listener in adapters?在适配器中分配接口侦听器的正确位置在哪里?
【发布时间】:2016-08-29 08:09:47
【问题描述】:

有时在 RecyclerView 适配器中,当您单击每一行中的项目时调用函数会很有帮助,因此我定义了一个接口并像这样分配侦听器:

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.RecyclerViewHolder> {
    private List<SomeObject> mSomeObjectList;
    private Context mContext;
    private RowClickListener mListener;

    public interface RowClickListener {
        void someFunction(SomeObject someObject);
    }

    public MyRecyclerViewAdapter(Context context, List<SomeObject> objects) {
        mContext = context;
        mSomeObjectList = objects;
        mListener = (RowClickListener) context;
    }
    //...

这是正确的方法吗?我注意到,当人们在 Fragment 类中分配侦听器时,他们通常在 OnAttach 方法中执行此操作,而在 Adapter 的情况下,这似乎并不存在。这里什么地方比较合适?

【问题讨论】:

  • 什么时候创建监听对象?

标签: java android interface android-recyclerview adapter


【解决方案1】:

宁可在Adapter 中定义它,我建议在FragmentActivity 中使用它。

Interface 定义单独的类或在Fragment/Activity 中定义它。

public class SomeActivity extends Activity implements RowClickListener
{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        .
        .
        .
        MyRecyclerViewAdapter adapter = new MyRecyclerViewAdapter(context,list,this);
    }

    @Override
    public void someFunction(SomeObject someObject){

    }
}

public interface RowClickListener {
    void someFunction(SomeObject someObject);
}

在你的适配器类中

private RowClickListener mListener;

public MyRecyclerViewAdapter(Context context, List<SomeObject> objects, RowClickListener listener) {
    mContext = context;
    mSomeObjectList = objects;
    mListener = listener;
}

【讨论】:

  • 我喜欢这种方法,但我什至不知道为什么!你这样做有什么特别的原因吗?
  • 一般来说,我之前为接口定义了单独的类,以便我可以多次使用它,没有其他原因。
  • 我通常将接口放在类中。你如何使它们成为单独的类?
  • 将其定义为单独的类没有区别,它与java类或活动或片段相同。只需在单独的文件中编写接口代码即可。
【解决方案2】:

是的,通过适配器构造函数传递侦听器很好。但是,请在投射前检查类型。

public MyRecyclerViewAdapter(Context context, List<SomeObject> objects) 
{
        mContext = context;
        mSomeObjectList = objects;

        if(context instanceOf RowClickListener)
        {
            mListener = (RowClickListener) context;
        }
    }

【讨论】:

  • 如何正常定义接口?大多数人是使用单独的文件还是将它们嵌套在另一个类中?
  • 如果接口只在单个类中使用,定义该类的接口即可。如果你在很多类中实现接口,那么考虑在单独的文件中定义接口。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
  • 2021-10-05
  • 2018-03-16
相关资源
最近更新 更多