我有一个基于RealmRecyclerViewAdapter的recyclerviewAdapter。
public class PlaceAdapter extends RealmRecyclerViewAdapter<Place, PlaceAdapter.PlaceViewHolder> implements Filterable {
private static final String TAG = PlaceAdapter.class.getSimpleName();
static class PlaceViewHolder extends RecyclerView.ViewHolder {
TextView name;
PlaceViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
}
}
private Realm realm;
private static RecyclerViewClickListener itemListener;
private TextView lastTextView;
public PlaceAdapter(@NonNull Context context, @Nullable OrderedRealmCollection data, boolean autoUpdate, RecyclerViewClickListener listener,
Realm realm) {
super(context, data, autoUpdate);
this.realm = realm;
itemListener = listener;
}
@Override
public PlaceViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).
inflate(R.layout.place_item_layout, viewGroup, false);
return new PlaceViewHolder(itemView);
}
@Override
public void onBindViewHolder(final PlaceViewHolder holder, final int position) {
final Place place = getData().get(position);
holder.name.setText(place.getName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemListener.recyclerViewListClicked(place.getId());
holder.name.setTypeface(Typeface.create(holder.name.getTypeface(), Typeface.BOLD), Typeface.BOLD);
if (lastTextView != null && lastTextView != holder.name) {
lastTextView.setTypeface(Typeface.create(lastTextView.getTypeface(), Typeface.NORMAL), Typeface.NORMAL);
}
notifyItemRangeChanged(0, getItemCount());
lastTextView = holder.name;
}
});
}
@Override
public int getItemCount() {
return getData().size();
}
@Override
public Filter getFilter() {
final Filter filter = new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
String text = constraint.toString();
if (text == null || "".equals(text)) {
updateData(realm.where(Place.class).findAll());
} else {
updateData(realm.where(Place.class)
.contains("name", text, Case.INSENSITIVE) // TODO: change field
.findAll());
}
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
return results;
}
};
return filter;
}
public interface RecyclerViewClickListener {
void recyclerViewListClicked(int placeId);
}
}
问题是当我滚动回收器视图时,顶部的那些视图不可见,我点击视图,它上面的视图得到粗体字体。只有当我第二次点击它时,正确的视图才会变成粗体字样。
答案 0 :(得分:5)
我认为您忘记在适配器中覆盖这些方法:
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return position;
}
我不确定为什么会发生这种情况,但滚动时对于Recyclerview混乱问题是正确的解决方案。