RecyclerView-在特定位置获取视图


139

我有一个与RecyclerView和一起进行的活动ImageView。我正在使用RecyclerView来水平显示图像列表。当我点击在图像上RecyclerViewImageView在活动中应显示图像的大局观。到目前为止,一切正常。

现在ImageButtons,活动中还有两个:imageButton_leftimageButton_right。当我单击时imageButton_left,中的图像ImageView应左移,并且中的缩略图也RecyclerView应反映此更改。与的情况类似imageButton_right

我能够旋转ImageView。但是,如何旋转缩略图RecyclerView?我如何获得ViewHolderImageView

码:

活动XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/original_image"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:scaleType="fitXY"
            android:src="@drawable/image_not_available_2" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center_horizontal"
            android:orientation="horizontal">


            <ImageButton
                android:id="@+id/imageButton_left"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="20dp"
                android:background="@drawable/rotate_left_icon" />

            <ImageButton
                android:id="@+id/imageButton_right"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/rotate_right_icon" />

        </LinearLayout>
    </LinearLayout>
</LinearLayout>

我的活动代码:

public class SecondActivity extends AppCompatActivity implements IRecyclerViewClickListener {


    RecyclerView mRecyclerView;
    LinearLayoutManager mLayoutManager;
    RecyclerViewAdapter mRecyclerViewAdapter;
    List<String> urls = new ArrayList<String>();
    ImageView mOriginalImageView;
    ImageButton mLeftRotate, mRightRotate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        urls.clear();

        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        mLayoutManager = new LinearLayoutManager(this, android.support.v7.widget.LinearLayoutManager.HORIZONTAL, false);
        mLayoutManager.setOrientation(android.support.v7.widget.LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerViewAdapter = new RecyclerViewAdapter(this, urls);
        mRecyclerView.setAdapter(mRecyclerViewAdapter);

        mOriginalImageView = (ImageView) findViewById(R.id.original_image);
        mLeftRotate = (ImageButton) findViewById(R.id.imageButton_left);
        mLeftRotate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOriginalImageView.setRotation(mOriginalImageView.getRotation() - 90);
            }
        });


        mRightRotate = (ImageButton) findViewById(R.id.imageButton_right);
        mRightRotate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOriginalImageView.setRotation(mOriginalImageView.getRotation() + 90);
            }
        });

        Intent intent = getIntent();
        if (intent != null) {

            String portfolio = intent.getStringExtra("portfolio");

            try {

                JSONArray jsonArray = new JSONArray(portfolio);

                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    String url = jsonObject.getString("url");
                    urls.add(url);
                }

                Log.d(Const.DEBUG, "URLs: " + urls.toString());

                mRecyclerViewAdapter.notifyDataSetChanged();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }


    @Override
    public void onItemClick(int position) {
        Picasso.with(this).load(urls.get(position)).into(mOriginalImageView);
    }
}

我的RecyclerView自定义适配器:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    Context context;
    List<String> mUrls = new ArrayList<String>();

    IRecyclerViewClickListener mIRecyclerViewClickListener;

    public int position;

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }



    public RecyclerViewAdapter(Context context, List<String> urls) {
        this.context = context;
        this.mUrls.clear();
        this.mUrls = urls;

        Log.d(Const.DEBUG, "Urls Size: " + urls.size());
        Log.d(Const.DEBUG, urls.toString());

        if (context instanceof IRecyclerViewClickListener)
            mIRecyclerViewClickListener = (IRecyclerViewClickListener) context;
        else
            Log.d(Const.DEBUG, "Implement IRecyclerViewClickListener in Activity");
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_horizontal_recyclerview, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Picasso.with(context).load(mUrls.get(position)).into(holder.mImageView);
    }

    @Override
    public int getItemCount() {
        return mUrls.size();
    }


    public void rotateThumbnail() {


    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public ImageView mImageView;
        public View v;

        public ViewHolder(View v) {
            super(v);
            v.setTag(getAdapterPosition());
            v.setOnClickListener(this);
            this.mImageView = (ImageView) v.findViewById(R.id.image);
        }

        @Override
        public void onClick(View v) {
            this.v = v;
            mIRecyclerViewClickListener.onItemClick(getAdapterPosition());
        }
    }


}

1
您应该在viewHolder构造函数中创建它,添加一个属性,该属性将告诉您是否需要旋转图像,然后只需在数据上更改该属性,然后调用notifyDataSetChanged即可重新加载recyclerView
Nanoc 2015年

有任何答案可以解决您的问题吗?
Scott Biggs

对于性能问题,ViewHolder应该是静态的。来自外部类的所有变量都应通过构造函数传递。
AppiDevo

作为
mut tony

Answers:


149

我想您正在使用a LinearLayoutManager来显示列表。它有所谓的一个很好的方法findViewByPosition

查找代表给定适配器位置的视图。

您需要的只是您感兴趣的商品的适配器位置。

编辑:正如Paul Woitaschek在评论中指出的那样findViewByPosition是一种方法,LayoutManager因此它可以与所有LayoutManagers一起使用(例如StaggeredGridLayoutManager,等等)。


9
多数民众赞成实际上是的方法,LayoutManager因此这将适用于所有LayoutManager子类。
Paul Woitaschek '16

看了源代码。当不在prelayout中时,LinearLayoutManger会通过DirectAccess在支持数组上查找,而recyclerView方法始终会遍历。因此,此方法可能更有效。
NameSpace 2013年

嘿@stanO,您能用这个stackoverflow.com/questions/49952965/…

3
返回:视图-代表给定位置的子视图;如果未布置该位置,则返回null ... recyclerview->大多数东西返回null
me_

请记住,您必须等待适配器添加到列表中,有关详细信息,请参见下面的答案
Konstantin Konopko '19

241

这就是您要寻找的

我也有这个问题。和您一样,很难找到答案。但是有一种简单的方法可以从特定位置获取ViewHolder(您可能会在Adapter中做很多事情)。

myRecyclerView.findViewHolderForAdapterPosition(pos);

注意: 如果视图已被回收,它将返回null。感谢迈克尔迅速赶上了我的重要遗漏。


3
这正是我在LayoutManager中寻找的东西
Ed Lee

12
这是可行的,但是,如果ViewHolder您要引用的对象被“回收”,它将返回null
迈克尔(Michael)

5
@Michael,赶上!这是对所有人的警告,请先测试null(是的,就像Android中的所有其他功能一样)!
Scott Biggs

1
我们可以从适配器内部执行此操作吗?
Mauker

2
@Mauker:您可以从任何可以访问RecyclerView实例的对象中使用它。
Scott Biggs

27

如果需要View,请确保itemView像这样访问ViewHolder 的属性:myRecyclerView.findViewHolderForAdapterPosition(pos).itemView;


11

您可以同时使用

recyclerViewInstance.findViewHolderForAdapterPosition(adapterPosition)recyclerViewInstance.findViewHolderForLayoutPosition(layoutPosition)。确保RecyclerView视图使用两种类型的位置

适配器位置:项目在适配器中的位置。从适配器的角度来看,这是位置。版面位置:项目在最新版面计算中的位置。从LayoutManager的角度来看,这是位置。您应该使用getAdapterPosition()findViewHolderForAdapterPosition(adapterPosition)getLayoutPosition()findViewHolderForLayoutPosition(layoutPosition)

选取一个成员变量来保存先前在recyclerview适配器中选择的项目位置,并使用另一个成员变量来检查用户是否是第一次单击。

底部附有示例代码和屏幕截图,以获取更多信息。

public class MainActivity extends AppCompatActivity {     

private RecyclerView mRecyclerList = null;    
private RecyclerAdapter adapter = null;    

@Override    
protected void onCreate(Bundle savedInstanceState) {    
    super.onCreate(savedInstanceState);    
    setContentView(R.layout.activity_main);    

    mRecyclerList = (RecyclerView) findViewById(R.id.recyclerList);    
}    

@Override    
protected void onStart() {    
    RecyclerView.LayoutManager layoutManager = null;    
    String[] daysArray = new String[15];    
    String[] datesArray = new String[15];    

    super.onStart();    
    for (int i = 0; i < daysArray.length; i++){    
        daysArray[i] = "Sunday";    
        datesArray[i] = "12 Feb 2017";    
    }    

    adapter = new RecyclerAdapter(mRecyclerList, daysArray, datesArray);    
    layoutManager = new LinearLayoutManager(MainActivity.this);    
    mRecyclerList.setAdapter(adapter);    
    mRecyclerList.setLayoutManager(layoutManager);    
}    
}    


public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyCardViewHolder>{          

private final String TAG = "RecyclerAdapter";        
private Context mContext = null;        
private TextView mDaysTxt = null, mDateTxt = null;    
private LinearLayout mDateContainerLayout = null;    
private String[] daysArray = null, datesArray = null;    
private RecyclerView mRecyclerList = null;    
private int previousPosition = 0;    
private boolean flagFirstItemSelected = false;    

public RecyclerAdapter(RecyclerView mRecyclerList, String[] daysArray, String[] datesArray){    
    this.mRecyclerList = mRecyclerList;    
    this.daysArray = daysArray;    
    this.datesArray = datesArray;    
}    

@Override    
public MyCardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {    
    LayoutInflater layoutInflater = null;    
    View view = null;    
    MyCardViewHolder cardViewHolder = null;    
    mContext = parent.getContext();    
    layoutInflater = LayoutInflater.from(mContext);    
    view = layoutInflater.inflate(R.layout.date_card_row, parent, false);    
    cardViewHolder = new MyCardViewHolder(view);    
    return cardViewHolder;    
}    

@Override    
public void onBindViewHolder(MyCardViewHolder holder, final int position) {    
    mDaysTxt = holder.mDaysTxt;    
    mDateTxt = holder.mDateTxt;    
    mDateContainerLayout = holder.mDateContainerLayout;    

    mDaysTxt.setText(daysArray[position]);    
    mDateTxt.setText(datesArray[position]);    

    if (!flagFirstItemSelected){    
        mDateContainerLayout.setBackgroundColor(Color.GREEN);    
        flagFirstItemSelected = true;    
    }else {    
        mDateContainerLayout.setBackground(null);    
    }    
}    

@Override    
public int getItemCount() {    
    return daysArray.length;    
}    

class MyCardViewHolder extends RecyclerView.ViewHolder{    
    TextView mDaysTxt = null, mDateTxt = null;    
    LinearLayout mDateContainerLayout = null;    
    LinearLayout linearLayout = null;    
    View view = null;    
    MyCardViewHolder myCardViewHolder = null;    

    public MyCardViewHolder(View itemView) {    
        super(itemView);    
        mDaysTxt = (TextView) itemView.findViewById(R.id.daysTxt);    
        mDateTxt = (TextView) itemView.findViewById(R.id.dateTxt);    
        mDateContainerLayout = (LinearLayout) itemView.findViewById(R.id.dateContainerLayout);    

        mDateContainerLayout.setOnClickListener(new View.OnClickListener() {    
            @Override    
            public void onClick(View v) {    
                LinearLayout linearLayout = null;    
                View view = null;    

                if (getAdapterPosition() == previousPosition){    
                    view = mRecyclerList.findViewHolderForAdapterPosition(previousPosition).itemView;    
                    linearLayout = (LinearLayout) view.findViewById(R.id.dateContainerLayout);    
                    linearLayout.setBackgroundColor(Color.GREEN);    
                    previousPosition = getAdapterPosition();    

                }else {    
                    view = mRecyclerList.findViewHolderForAdapterPosition(previousPosition).itemView;    
                    linearLayout = (LinearLayout) view.findViewById(R.id.dateContainerLayout);    
                    linearLayout.setBackground(null);    

                    view = mRecyclerList.findViewHolderForAdapterPosition(getAdapterPosition()).itemView;    
                    linearLayout = (LinearLayout) view.findViewById(R.id.dateContainerLayout);    
                    linearLayout.setBackgroundColor(Color.GREEN);    
                    previousPosition = getAdapterPosition();    
                }    
            }    
        });    
    }    
}       

} 选择的第一个元素 第二个元素已选择,而先前选择的项目变为未选择 第五个元素已选中,先前选择的项目变为未选中


我以为讨论已经筋疲力尽了!感谢您进一步澄清此问题。
Scott Biggs

2
在这里,当我尝试更改上一个项目的颜色时,我在else块中得到了NullPointer异常,因此我添加了null检查,现在如果它具有NullPointer异常,则永远不会进入该块,因此上一个项目的颜色永远不会改变。现在,我的“回收者”视图中的项目带有多个彩色项目。我该如何解决
Abhilash Reddy

8

您可以使ViewHolder的ArrayList:

 ArrayList<MyViewHolder> myViewHolders = new ArrayList<>();
 ArrayList<MyViewHolder> myViewHolders2 = new ArrayList<>();

并且,所有ViewHolder都存储在列表中,例如:

 @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
        final String str = arrayList.get(position);

        myViewHolders.add(position,holder);
}

并根据需要在ArrayList中添加/删除其他ViewHolder。


谢谢您,我努力争取2天的可回收持有人。
nimi0112 '18

5

您可以使用以下方法在recyclerview上获取特定位置的视图

int position = 2;
RecyclerView.ViewHolder viewHolder = recyclerview.findViewHolderForItemId(position);
View view = viewHolder.itemView;
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);

5

您可以简单地使用回收者视图的“ findViewHolderForAdapterPosition ”方法,然后从中获得一个viewHolder对象,然后将该视图持有者转换为适配器视图持有者,以便您可以直接访问您的视图持有者的视图

以下是kotlin的示例代码

 val viewHolder = recyclerView.findViewHolderForAdapterPosition(position)
 val textview=(viewHolder as YourViewHolder).yourTextView

4

请记住,您必须等到适配器将添加到列表中,然后才能尝试按位置获取视图

final int i = 0;
recyclerView.setAdapter(adapter);
recyclerView.post(new Runnable() {
    @Override
    public void run() {
        View view = recyclerView.getLayoutManager().findViewByPosition(i);
    }
});

2
如果您添加多个项目(即:如果您有一个将其添加并快速按下的按钮),则此方法并不总是有效。您应该添加具有延迟的可运行对象。
Alex Burdusel

3

要从recyclerView的特定位置获取视图,您需要在recyclerView对象上调用findViewHolderForAdapterPosition(position),该对象将返回RecyclerView.ViewHolder

从带有itemView的返回的RecyclerView.ViewHolder对象中,您可以访问该特定位置的所有View

RecyclerView.ViewHolder rv_view = recyclerView.findViewHolderForAdapterPosition(position);

ImageView iv_wish = rv_view.itemView.findViewById(R.id.iv_item);

1

您也可以执行此操作,这在您想要在单击recyclerview位置项后修改视图时会有所帮助

@Override
public void onClick(View view, int position) {

            View v =  rv_notifications.getChildViewHolder(view).itemView;
            TextView content = v.findViewById(R.id.tv_content);
            content.setText("Helloo");

        }

1

要从回收者视图列表中获取特定视图,或在回收者视图的edittext中显示错误。

private void popupErrorMessageAtPosition(int itemPosition) {

    RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(itemPosition);
    View view = viewHolder.itemView;
    EditText etDesc = (EditText) view.findViewById(R.id.et_description);
    etDesc.setError("Error message here !");
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.