我在点击CardView时遇到了一个问题。我有一个带有CardViews的RecyclerView,我想在其中进行单次选择。第一次点击正确,但当我点击另一个时,前一个CardView的文本颜色变成了白色。
下面是我的适配器的代码。
holder.setiRecyclerItemSelectedListener(new IRecyclerItemSelectedListener() {
@Override
public void onItemSelectedListener(View view, int pos) {
// Loop all cards in card list
for (CardView cardView: cardViewList) {
if (cardView.getTag() == null) // Only available card time slots
{
cardView.setCardBackgroundColor(context.getColor(R.color.colorWhite));
holder.txt_time_slot.setTextColor(context.getColor(android.R.color.tab_indicator_text));
holder.txt_time_slot_description.setTextColor(context.getColor(android.R.color.tab_indicator_text));
}
}
// Color of selected card time slot
holder.card_time_slot.setCardBackgroundColor(context.getColor(R.color.colorPrimaryLight));
holder.txt_time_slot.setTextColor(context.getColor(R.color.colorWhite));
holder.txt_time_slot_description.setTextColor(context.getColor(R.color.colorWhite));
// Send broadcast to enable button NEXT
Intent intent = new Intent(Common.KEY_ENABLE_BUTTON_NEXT);
intent.putExtra(Common.KEY_TIME_SLOT, position); // Put index of time slot we have selected
intent.putExtra(Common.KEY_STEP, 3);
localBroadcastManager.sendBroadcast(intent);
}
});
图片。
第一个正确
第二个没有
在适配器中定义一个选定的索引。
int selectedIndex = -1;
你可以用这个方法访问recyclerView的子程序。
findViewHolderForAdapterPosition(position);
改变onClicklistener。
if (selectedIndex != -1)
{
YourHolder holderOld = (YourHolder) recycleView.findViewHolderForAdapterPosition(selectedIndex);
holderOld.cardView.setCardBackgroundColor(context.getColor(R.color.colorWhite));
holderOld.txt_time_slot.setTextColor(context.getColor(android.R.color.tab_indicator_text));
holderOld.txt_time_slot_description.setTextColor(context.getColor(android.R.color.tab_indicator_text));
}
selectedIndex = pos;
holder.card_time_slot.setCardBackgroundColor(context.getColor(R.color.colorPrimaryLight));
holder.txt_time_slot.setTextColor(context.getColor(R.color.colorWhite));
holder.txt_time_slot_description.setTextColor(context.getColor(R.color.colorWhite));
我想你应该在RecyclerView中使你的视图无效。所以根据你的问题,我认为你应该调用 notifyDataSetChanged()
函数,或者您应该通过调用 notifyItemChanged(position)
. 希望对你有帮助
我以为你暗示的颜色的选择卡时间功能出来了 }
使用它的机器,并在不改变之前的功能的情况下结束它,这可能会有帮助。