Android Listview项目删除

时间:2017-01-02 14:57:38

标签: android listview adapter

我想删除setOnItemLongClickListener中的项目,删除不起作用。任何人都可以看到代码中的问题是什么吗?

适配器

public abstract class myArrayAdapter<T> extends ArrayAdapter<T> {

    protected List<T> items = new ArrayList<>();

    protected int resource;
    protected LayoutInflater layoutInflater;

    public myArrayAdapter(Context context, int resource) {
        super(context, resource);
        this.resource = resource;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = layoutInflater.inflate(resource, null, false);
        getView(position, getItem(position), view);
        return view;
    }

    public abstract void getView(int position, T model, View view);

    public void setItems(List<T> items) {
        this.items = items;
        notifyDataSetChanged();
    }

    @Override
    public T getItem(int position) {
        return items.get(position);
    }

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

    public List<T> getItems() {
        return items;
    }

    @Override
    public int getPosition(T item) {
        return items.indexOf(item);
    }

}

我的活动

public class QuoteDetailActivity extends Activity {

    @Inject
    QuoteDetailViewModel viewModel;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.price_text)
    TextView priceTextView;

    @BindView(R.id.list_view_materials)
    ListView materialsListView;

    private int quoteId;

    myArrayAdapter<LinkedTreeMap<String, Object>> adapter;

    public static void start(Context context, int quoteId) {
        Intent starter = new Intent(context, QuoteDetailActivity.class);
        starter.putExtra("QUOTE_ID", quoteId);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quote_detail);
        ButterKnife.bind(this);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(v -> finish());

        quoteId = getIntent().getIntExtra("QUOTE_ID", 0);

        initMaterialList();
        bindToViewModel();
    }

    private void bindToViewModel() {

        viewModel.quoteModel()
                .compose(bindToLifecycle())
                .subscribe(quoteModel -> {
                    getSupportActionBar().setTitle(String.valueOf(quoteModel.get("QuoteName")));
                    priceTextView.setText(String.valueOf(quoteModel.get("TotalCost")) + " + KDV");
                });

        viewModel.quoteMaterialModel()
                .compose(bindToLifecycle())
                .subscribe(materialsModel -> {
                    adapter.setItems(materialsModel);
                });


        //teklif silme
        viewModel.materialDelete()
                .compose(bindToLifecycle())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        finish();
                    }
                });

        attachToViewModel(viewModel);
    }

    @Override
    protected void onResume() {
        super.onResume();
        viewModel.getQuoteDetail(quoteId);
    }

    private void initMaterialList(){
        adapter = new myArrayAdapter<LinkedTreeMap<String, Object>>(this, R.layout.layout_listview_item_quote_material) {
            @Override
            public void getView(int position, LinkedTreeMap<String, Object> model, View view) {
                TextView materialNameTextView = (TextView) view.findViewById(R.id.material_name);
                TextView priceAndAmountNameTextView = (TextView) view.findViewById(R.id.price_and_amount);
                TextView totalCostNameTextView = (TextView) view.findViewById(R.id.total_cost);

                materialNameTextView.setText(String.valueOf(model.get("MaterialName")));
                priceAndAmountNameTextView.setText("Fiy. x Mik : " + String.valueOf(model.get("Cost")) + " x " + String.valueOf(model.get("MaterialCount")));
                totalCostNameTextView.setText(String.valueOf(model.get("TotalCost")));
            }
        };
        materialsListView.setAdapter(adapter);


        materialsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                Resources r = getResources();
                int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
                int pxTop = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6, r.getDisplayMetrics());

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(QuoteDetailActivity.this);
                alertDialog.setTitle("Delete.");

                alertDialog.setPositiveButton("Yes", (dialog, which) -> {

                    LinkedTreeMap<String, Object> selectedItem = adapter.getItem(position);
                    int QuoteMaterialId = ((Double) selectedItem.get("QuoteMaterialId")).intValue();

                    viewModel.deleteMaterial(quoteId,QuoteMaterialId);

                    adapter.remove(adapter.getItem(position));
                    adapter.notifyDataSetChanged();

                });
                alertDialog.setNegativeButton("No", (dialog, which) -> {
                    dialog.dismiss();
                });

                alertDialog.show();
                return true;            }

        });



    }

    @Override
    public void setupComponent(ActivityComponent activityComponent) {
        DaggerQuoteComponent.builder()
                .activityComponent(activityComponent)
                .build()
                .inject(this);
    }

}

删除不会发生。我在哪里犯错误?感谢。

3 个答案:

答案 0 :(得分:1)

您必须使用数据集,而不是使用适配器。

例如:如果用ListView对象填充ArrayList<T>,如果要删除列表中的行,则必须从ArrayList中删除它,然后调用notifyDataSetChanged()

// ArrayList<T> items filled with data
// delete the item that you want
items.remove(position);
// so, communicate to the adapter that the dataset is changed
adapter.notifyDataSetChanged();

在您的特定情况下,来自materialsModel的项目,然后将其告知适配器,如下所示:

// remove the item
// I don't know which method you must call, hope you do ;)
materialsModel.remove(position)
// then notify the adapter that the dataset is changed
adapter.notifyDataSetChanged();

答案 1 :(得分:1)

尝试以下代码:

materialsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            Resources r = getResources();
            int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
            int pxTop = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6, r.getDisplayMetrics());

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(QuoteDetailActivity.this);
            alertDialog.setTitle("Delete.");

            alertDialog.setPositiveButton("Yes", (dialog, which) -> {

                LinkedTreeMap<String, Object> selectedItem = adapter.getItem(position);
                int QuoteMaterialId = ((Double) selectedItem.get("QuoteMaterialId")).intValue();

                viewModel.deleteMaterial(quoteId,QuoteMaterialId);

                adapter.remove(selectedItem);
                adapter.notifyDataSetChanged();
                //adapter.remove(adapter.getItem(position));
                //adapter.notifyDataSetChanged();

            });
            alertDialog.setNegativeButton("No", (dialog, which) -> {
                dialog.dismiss();
            });

            alertDialog.show();
            return true;            }

    });

答案 2 :(得分:0)

在MyArrayAdapter中使用带有列表项的不同构造函数

public MyArrayAdapter(Context context, int resource, List<T> objects) {
    super(context, resource, objects);
}

或覆盖适配器的remove方法并手动删除项目

@Override
public void remove(T object) {
    items.remove(object);        
}