2017-03-16 61 views
0

我目前使用RecyclerView但我無法解決問題; 如果用戶選擇了答案,請更改textview更改顏色和背景。 如果用戶選擇不同的答案先回答舊的textview顏色和背景。我如何可以RecyclerView不同視圖選擇或未選中

代碼;

@Override 
public void onBindViewHolder(final ViewHolder holder, int position) { 
    _mContext = holder._mAnswersContainer.getContext(); 
    _mPosition = position; 
    holder._mImageAnswer.setImageDrawable(Utils.stringToResource(_mContext, 
      _mAnswerList.get(_mPosition).mAnswerImage)); 
    holder._mImageTextAnswer.setText(_mAnswerList.get(_mPosition).mAnswerText); 

    holder._mAnswersContainer.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      holder._mImageTextAnswer.setTextColor(_mContext.getResources() 
        .getColor(R.color.white)); 
      holder._mImageTextAnswer.setBackgroundColor(_mContext.getResources() 
        .getColor(R.color.red)); 

      Log.d(TAG, "Values : " + QuestionsHelper.getInstance(_mContext) 
        .getValues(_mAnswerList.get(_mPosition).mAnswerText)); 

     } 
    }); 
} 

回答

1

您轉接器內,讓一個成員變量來跟蹤它的位置選擇:

private int mSelected = -1; 

內,您的onBindViewHolder(儘管它可能裏面onCreateViewHolder工作以及):

int color; 
if(position == mSelected){ 
    color = ContextCompat.getColor(context, R.color.selectedColor); 
}else{ 
    color = ContextCompat.getColor(context, R.color.regularColor); 
} 

// Set the color 
viewHolder.yourView.setBackgroundColor(color); 

爲您的RecyclerView適配器創建一些輔助功能來處理選擇:

public void selectPosition(int selected){ 
    mSelected = selected; 
    notifyDataSetChanged(); 
} 

public void resetSelected(){ 
    mSelected = -1; 
    notifyDataSetChanged(); 
} 

無論您想要設置選定的項目,只需致電adapter.selectPosition()即可。並用adapter.resetSelected()

清除選擇
相關問題