【发布时间】:2016-08-07 20:59:29
【问题描述】:
我有一个默认背景为白色的 CardView 的 RecyclerView 列表。我设置了一个 OnLongClickListener 来选择 CardView 并加载一个 DialogFragment 以确认删除项目(CardView)并将背景颜色更改为红色。
一切正常,除了列表中创建的第一个 CardView 已经显示红色背景,即使用户没有 OnLongClicked CardView。此后,添加的最新 CardView 始终显示红色背景,即使用户尚未 OnLongClicked CardView。我在这里错过了什么?
background_selector.xml:
...
<!-- Normal state. -->
<item android:drawable="@color/list_contact_item_default"
android:state_pressed="false"
android:state_selected="false" />
<!-- Selected state. -->
<item android:drawable="@color/item_selected"
android:state_pressed="false"
android:state_selected="true" />
</selector>
list_contact_tem.xml:
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/singlecard_view1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
card_view:cardCornerRadius="6dp"
card_view:cardElevation="4dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/background_selector">
...
适配器文件:
public class ContactListAdapter extends RecyclerView.Adapter<ContactListAdapter.ContactHolder>{
...
private int selectedPos;
@Override
public ContactHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_contact_item, parent, false);
final ContactHolder contactHolder = new ContactHolder(view);
// Attach a LongClick listener to the items's (row) view.
contactHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
// Save the new selected position.
selectedPos = contactHolder.getAdapterPosition(); // get the item position.
if (selectedPos != RecyclerView.NO_POSITION) {
if (recyclerItemClickListener != null) {
recyclerItemClickListener.onItemLongClick(selectedPos, contactHolder.itemView);
// Temporarily save the last selected position
int lastSelectedPosition = selectedPos;
// Update the previous selected row
notifyItemChanged(lastSelectedPosition);
notifyItemChanged(selectedPos);
}
}
return true;
}
});
return contactHolder;
}
@Override
public void onBindViewHolder(ContactHolder holder, int position) {
final Contact contact = contactList.get(position);
if(position == selectedPos) {
holder.itemView.setSelected(true);
} else {
holder.itemView.setSelected(false);
}
holder.thumb.setImageBitmap(letterBitmap);
holder.name.setText(contact.getName());
holder.phone.setText(contact.getPhone());
}
【问题讨论】:
标签: android android-recyclerview android-adapter