删除后如何更新ListView

时间:2018-10-08 08:10:59

标签: android-studio listview

在这里,我通过实现listAdapter来支持列表项中的“支持”按钮来使用“自定义适配器”。当我单击“删除”按钮时,它将删除当前行。但是我无法刷新此listView。

文件结构为MainActivity-> FragmentClass-> listAdpater的此自定义类。

public class Category_ListView_Custom_Adapter extends BaseAdapter implements ListAdapter{

private Realm realm;
private ArrayList<String> list = new ArrayList<>();
private Context context;

public Category_ListView_Custom_Adapter(ArrayList<String> list, Context context){
    this.list = list;
    this.context = context;
}

@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int i) {
    return list.get(i);
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
    View view1 = view;
    realm = Realm.getDefaultInstance();

    if(view == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.category_listview_row, null);
    }
    TextView listItemText = (TextView) view.findViewById(R.id.item);
    listItemText.setText(list.get(i));

    ImageView edit = (ImageView) view.findViewById(R.id.image);
    ImageView delete = (ImageView) view.findViewById(R.id.delete);

    edit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
     //       list.remove(i);
     ///       Toast.makeText(view.getContext(), "hey "+list.get(i).toString(), Toast.LENGTH_SHORT).show();
     //       notifyDataSetChanged();
            Intent intent = new Intent(context, AddCategory.class);
            intent.putExtra("category","expense");
            intent.putExtra("subcategory", list.get(i));
            context.startActivity(intent);
        }
    });

    delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            RealmResults<Category> categorylist = realm.where(Category.class).equalTo("Id",i+1).and().equalTo("Subcategory",list.get(i)).findAll();

            for (Category category : categorylist) {

                realm.beginTransaction();
                categorylist.deleteFirstFromRealm();
                realm.commitTransaction();

                try {
                    context.notifyAll();
                }catch (Exception e){
                    Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
                }

             //   Expense.call_resume
            }
        }
    });

    return view;
}

}

请帮助我。谢谢。

1 个答案:

答案 0 :(得分:0)

您正在从错误的视图中移除。尝试将根List <>设为静态,并执行Class.list.get(i).remove或类似的操作。

此外,尝试将视图隐藏在get视图中。