我正在使用RecyclerView并附加LinearLayoutManagerRecyclerView.Adapter

    RecyclerView conversationList = (RecyclerView)findViewById(R.id.conversationList);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    conversationList.setLayoutManager(layoutManager);
    MessagesAdapter adapter = new MessagesAdapter();
    conversationList.setAdapter(adapter);


onBindViewHolderRecyclerView.Adapter中,我使用setTag将适配器项对象传递给视图:

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {
        viewHolder.itemView.setTag(getItem(position));
        ...
    }


我正在遍历layoutManager的子视图并使用getTag方法获取所需的对象

        for (int i = 0; i < layoutManager.getChildCount(); i++) {
            LinearLayout container = (LinearLayout)layoutManager.getChildAt(i);
            LinearLayout container2 = (LinearLayout)container.getChildAt(0);
            Object tag = container2.getTag();
        }


对我来说似乎不对。有更好的方法吗?

最佳答案

当您滚动视图时,ViewHolder可能会被重用,因此将其重置。因此,您可能想获得的标签可能不正确。

关于android - 如何从LayoutManager View (RecyclerView)获取适配器项对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31857836/

10-13 05:46