我有一个RecyclerView
,其中包含ImageButton
。我想使用ImageButton的RecyclerView
事件中的新项目更新我的onClick()
。它适用于我的数据库,但它不会刷新我的RecyclerView。
@Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
final Quote current = data.get(position);
holder.quote.setText(current.getQuote());
holder.name.setText(current.getName());
holder.number.setText(String.valueOf(current.getId()));
if (current.getIsLiked()==1){
holder.quote.setTextColor(Color.parseColor("#c0392b"));
holder.name.setTextColor(Color.parseColor("#e74c3c"));
holder.relativeLayout.setBackgroundColor(Color.parseColor("#ecf0f1"));
}else if (current.getIsLiked()==0){
holder.quote.setTextColor(Color.parseColor("#ffffff"));
holder.name.setTextColor(Color.parseColor("#fefefefe"));
holder.relativeLayout.setBackgroundColor(Color.parseColor("#F5F5F5"));
holder.relativeLayout.getBackground().setAlpha(11);
}
holder.imgIsLiked.setOnClickListener(new View.OnClickListener() {
DataBaseHelper db=new DataBaseHelper(context);
@Override
public void onClick(View v) {
if (current.getIsLiked()==0){
db.updateDatabase(current.getId(), 1);
swap();
}
else if (current.getIsLiked()==1){
db.updateDatabase(current.getId(), 0);
swap();
}
}
});
}
private void swap(){
List<Quote> data2 = new ArrayList<Quote>(data);
data.clear();
data.addAll(data2);
notifyDataSetChanged();
}
这是我的脆弱:
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedState){
setHasOptionsMenu(true);
View view=inflater.inflate(R.layout.quotes_fragment,container,false);
recyclerView= (RecyclerView) view.findViewById(R.id.quotes_fragment_recyclerView);
DataBaseHelper dataBaseHelper=new DataBaseHelper(getContext());
adapter = new QuoteAdapter(getContext(), dataBaseHelper.getAllData());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
return view;
}
更新: 感谢Selvin,解决方案是:
holder.imgIsLiked.setOnClickListener(new View.OnClickListener() {
DataBaseHelper db = new DataBaseHelper(context);
@Override
public void onClick(View v) {
if (current.getIsLiked() == 0) {
current.setIsLiked(1);
db.updateDatabase(current.getId(), 1);
notifyDataSetChanged();
} else if (current.getIsLiked() == 1) {
db.updateDatabase(current.getId(), 0);
current.setIsLiked(0);
notifyDataSetChanged();
}
}
});
答案 0 :(得分:0)
在onClick函数
上尝试此函数调用public void foo(int position) {
data.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, list.size());
}