我使用RecyclerView显示可以选择的项目。但是,当所选项目通过Firestore事务更新时,选择将消失。我假设它在更新的项目上调用notifyItemChanged,但我不知道如何保留它的选定状态。我正在使用此代码来选择项目:
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int currentPosition = holder.getLayoutPosition();
if(selectedPosition != currentPosition){
// Temporarily save the last selected position
int lastSelectedPosition = selectedPosition;
// Save the new selected position
selectedPosition = currentPosition;
// update the previous selected row
notifyItemChanged(lastSelectedPosition);
// select the clicked row
holder.itemView.setSelected(true);
}
}
});
和此代码突出显示布局:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Color when the row is selected -->
<item android:drawable="@android:color/darker_gray" android:state_pressed="false" android:state_selected="true" />
<!-- Standard background color -->
<item android:drawable="@android:color/white" android:state_selected="false" />
</selector>