簡體   English   中英

不需要選擇的recyclerview項目

[英]Unwanted selection of recyclerview item

viewHolder.optiontxt1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {


    viewHolder.optiontxt1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.check, 0, 0, 0);
                    Log.e("position", "onClick: " + i);
                }
            });

這就是我實際上要做的事情,有6個數組,我在其中顯示數據以在recyclerView中顯示第一個數組,第二個問題是問題,第四個數組是四個選項。 但問題是,當我選擇第一個問題的選項之一時,選項會自動選擇八個問題中的一個

recyclerview回收OnBindViewHolder的視圖。因此,當單擊items ,它會反映在其他一些positions

為了更好地了解recyclerview選擇狀態, 請參閱此示例

希望它會對你有所幫助。

Recyclerview回收它的項目視圖。 在您的情況下,recyclerview在第八個問題中重復使用第一個問題的視圖。 這可以是任何問題。 我們必須使用onBindViewHolder中的更新內容更新每個itemview。 你能做的就是保持陣列的答案。 當用戶單擊選項時,更新答案數組並為該位置調用notifyitemchanged。 在onBindViewHolder中,通過選中答案數組來選擇/取消選擇選項。 這是代碼片段。

int[] answers = new int[getItemCount()];

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
    /* check/uncheck options by checking the answer array */
    if(answers[position] == 1)  viewHolder.optiontxt1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.check, 0, 0, 0);
    else  viewHolder.optiontxt1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.uncheck, 0, 0, 0);

    if(answers[position] == 2)  viewHolder.optiontxt2.setCompoundDrawablesWithIntrinsicBounds(R.drawable.check, 0, 0, 0);
    else  viewHolder.optiontxt2.setCompoundDrawablesWithIntrinsicBounds(R.drawable.uncheck, 0, 0, 0);

    if(answers[position] == 3)  viewHolder.optiontxt3.setCompoundDrawablesWithIntrinsicBounds(R.drawable.check, 0, 0, 0);
    else  viewHolder.optiontxt3.setCompoundDrawablesWithIntrinsicBounds(R.drawable.uncheck, 0, 0, 0);

    if(answers[position] == 4)  viewHolder.optiontxt4.setCompoundDrawablesWithIntrinsicBounds(R.drawable.check, 0, 0, 0);
    else  viewHolder.optiontxt4.setCompoundDrawablesWithIntrinsicBounds(R.drawable.uncheck, 0, 0, 0);

    viewHolder.optiontxt1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            answers[position] = 1;
           notifyItemChanged(position);
        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM