如何获取 RecyclerView 的特定项目视图?

ano*_*ous 4 android android-recyclerview

其实我想RecyclerView在我的fragment.class. 为此,我尝试getter在我的adapter班级中设置 a然后尝试在 my 中访问它,fragment但我无法访问 views 。

适配器类代码:

private List<ViewHolder> holder_list=new ArrayList<>();
 @Override
public void onBindViewHolder(ViewHolder holder, int position) {

    holder_list.add(holder);
   }
public ViewHolder getViewHolder(int position){
    return holder_list.get(position);
}
Run Code Online (Sandbox Code Playgroud)

片段代码:

MessageAdapter.ViewHolder holder= msgAdp.getViewHolder(msgAdp.getItemCount()-1);
    //Here holder.mMessageView is a text view
Toast.makeText(ctx,holder.mMessageView.getText().toString(),Toast.LENGTH_SHORT).show();
Run Code Online (Sandbox Code Playgroud)

Khe*_*raj 9

这是最简单的方法

如果你想获得项目的 ViewHolder。

RecyclerView.ViewHolder viewHolder = rvList.getChildViewHolder(rvList.getChildAt(0));
Run Code Online (Sandbox Code Playgroud)

或者如果您想获取项目的 View 对象。

View view = rvList.getChildAt(0);
Run Code Online (Sandbox Code Playgroud)

使用您需要的那个。您可以获取视图或 ViewHolder。您可以根据需要操纵它们。

编辑:

getChildAt 方法是可靠的,因为我也遇到了一段时间的问题,可能还没有解决。

您可以使用此代码

RecyclerView.ViewHolder holder = (RecyclerView.ViewHolder)
recyclerView.findViewHolderForAdapterPosition(position);
if (null != holder) {
   holder.itemView.findViewById(R.id.xyz).setVisibility(View.VISIBLE);
}
Run Code Online (Sandbox Code Playgroud)

编辑 2:注意

这是一个已知问题,如果您在设置列表后立即调用 findViewHolderForAdapterPosition,则会收到 NullPointerException。

if notifyDataSetChanged() has been called but the new layout has not been calculated yet, this method will return null since the new positions of views are unknown until the layout is calculated.

link

For solving this you can do like this.

recyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                RecyclerView.ViewHolder holder = (RecyclerView.ViewHolder)
                recyclerView.findViewHolderForAdapterPosition(position);
                if (null != holder) {
                    holder.itemView.findViewById(R.id.xyz).setVisibility(View.VISIBLE);
                }
            }
        }, 50);
Run Code Online (Sandbox Code Playgroud)