【发布时间】:2019-07-10 19:08:06
【问题描述】:
我不明白为什么将监听器应用于持有者是有效的。
我一天中的大部分时间都在看文章。 stackoverflow 上的主题很好地涵盖了范围。 我发现的选择:
- 附加到 TextView - 创建多个侦听器。
- 附加到 ViewHolder - 再次创建多个侦听器,除非您创建一个侦听器然后使用它来附加,您也可以使用 TextView 执行此操作。
- 附加 onItemTouchListener - 一种非常复杂的方法。
我没有看到只是一个简单的工具View.OnClickListener 连接到适配器。如果您这样做,则生成一个public void onClick(View view),并为适配器提供RecyclerView 的副本,然后将适配器(this)作为侦听器分配给您在onCreateViewHolder 中膨胀的项目视图。然后通过RecyclerViewgetChildAdapterPosition函数访问仓位。见代码 sn-ps。
//create adapter class implementing the on click listener
public class WordListAdapter extends RecyclerView.Adapter<WordListAdapter.WordViewHolder> implements View.OnClickListener {
private final LinkedList<String> mWordList;
private LayoutInflater mInFlater;
private final RecyclerView recyclerView;
//in constructor, pass in RecyclerView created in MainActivity
public WordListAdapter(Context context, LinkedList<String> wordList, RecyclerView rView) {
recyclerView = rView; <----
mInFlater = LayoutInflater.from(context);
this.mWordList = wordList;
}
//implementation of View.OnClickListener makes
@Override
public void onClick(View view) {
//get the position of the item that was clicked
int mPosition = recyclerView.getChildAdapterPosition(view); <----
//other code to do what you want with the list(eg. String element = mWordList.get(mPosition);)
}
//And you set your pointer in the adapter class
@Override
public WordListAdapter.WordViewHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType) {
View mItemView = mInFlater.inflate(R.layout.wordlist_item, parent, false);
mItemView.setOnClickListener(this); <----
return new WordViewHolder(mItemView, this);
}
在我看来,这个答案很简单,并且具有单击侦听器上的单个线程的优势,所有线程都在列表适配器中处理。
我想,我主要是想在一个封闭的话题上分享我的解决方案,但我当然欢迎任何关于为什么这可能不会更好的建议。这实际上是我在 Android 基础知识 04.5 RecyclerView 中挑战 2 的解决方案。
【问题讨论】:
-
对不起,文字很笨拙。我不知道它会大大简化文本的格式。我现在看到编辑器中有更多的格式化功能。
-
Why is it suggested你应该问建议的人,而不是我们。 -
好点弗拉德!希望它现在对研究该主题的人有用?
-
感谢整理文字的人!让我的项目符号列表栩栩如生。
-
好的,我想我明白了。感谢 W0rmH0le 的编辑。
标签: android performance android-recyclerview onclicklistener