我想在长按列表视图项目时将其删除。删除项目后,我需要重新启动活动以查看更改,但我想立即查看更改
我已经尝试过notifyDataSetChanged();但是它没有用,我从sqlite数据库中获取数据,并将其放入哈希图中,然后将其发送到自定义适配器 长按时,将从数据库中删除一行,但列表视图中未进行任何更改。
@Override
public View getView( final int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
ImageView imageView = view.findViewById(R.id.detailsimage);
CardView cardView = view.findViewById(R.id.detailcardView);
TextView textmo =view.findViewById(R.id.detailsmo);
TextView texttu =view.findViewById(R.id.detailstu);
TextView textwe =view.findViewById(R.id.detailswe);
TextView textth =view.findViewById(R.id.detailsthu);
TextView textfr =view.findViewById(R.id.detailsfri);
TextView textsa =view.findViewById(R.id.detailssat);
TextView textsu =view.findViewById(R.id.detailssun);
final databasehandler db = new databasehandler(context);
cardView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
db.deleteTitle(position+1);
Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
return true;
}
});
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
HashMap<String, String> hashmap= arrayList.get(position);
String string= hashmap.get("repeat");
string = Objects.requireNonNull(string).trim();
Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
}
});
HashMap<String, String> hashmap= arrayList.get(position);
String string= Objects.requireNonNull(hashmap.get("repeat")).trim();
String[] separated = Objects.requireNonNull(string).split("");
}
}}
return view;
}
}
答案 0 :(得分:0)
将列表传递到适配器并更改该块
cardView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
db.deleteTitle(position+1);
yourList.remove(position);
Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
return true;
}
});
答案 1 :(得分:0)
那么,您应该在自定义适配器中重新加载数据。根据您的描述,我了解到它与数据库没有任何绑定,那么为什么即使调用notifyDataSetChange()
后也希望它重新加载?当您在适配器中注册了实际的观察者时,notifyDataSetChange
才能工作。
请查看Loaders
和Content Providers
,以便自动反映ListView
中的数据库状态。这是链接-https://developer.android.com/guide/components/loaders
答案 2 :(得分:0)
您不应该调用notifyDataSetChanged
,它会刷新整个列表,这会影响性能
cardView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
db.deleteTitle(position+1);
yourArrayList.remove(position);
Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
notifyItemRemoved(position);
return true;
}
});
答案 3 :(得分:0)
请创建自定义数组列表:-
List<Integer> al = new ArrayList<>();
al.add("item 1");
al.add("item 2");
al.add("item 3");
al.add("item 4");
al.add("item 5");
设置适配器:-
StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, a1);
listview.setAdapter(adapter);
从位置删除项目
al.remove(position);
现在刷新列表视图适配器:-
adapter.notifyDataSetChanged();