从getView

时间:2015-09-24 19:51:51

标签: java android listview android-arrayadapter

我正在制作一个购物车应用,用户可以在购物车中添加和删除商品。当用户查看他们的购物车时,会显示他们添加的商品列表。此列表使用ArrayAdapter创建。每行包含一个删除按钮,用户可以从购物车中删除该项目。我已经成功地从Cart对象中删除了该项目。但是,当用户单击“删除”按钮时,我在更新屏幕时遇到了麻烦。我听说过适配器的notifydatasetchanged()方法,但我不知道如何在getView中的OnClickListener中实现它。这是代码:

CartScreen.java

package com.livilatenight.livilatenight;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;

import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SaveCallback;

public class CartScreen extends ActionBarActivity {

    ListView items;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart_screen);

        final ParseUser current = ParseUser.getCurrentUser();

        try{
            Cart userCart = (Cart) current.fetchIfNeeded().get("cart");
            String[] itemNames = userCart.getItems();
            String[] itemPrices = userCart.getPrices();
            int[] quantities = userCart.getQuantities();
            Integer[] itemPictures = userCart.getPictures();

            CartListAdapter adapter = new CartListAdapter(CartScreen.this, itemNames,itemPrices,quantities,itemPictures);
            items = (ListView) findViewById(R.id.listView);
            items.setAdapter(adapter);
        }catch(ParseException e){
            Toast.makeText(CartScreen.this, e.toString(),Toast.LENGTH_LONG).show();
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_cart_screen, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

CartListAdapter.java

package com.livilatenight.livilatenight;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.ParseUser;

public class CartListAdapter extends ArrayAdapter<String> {

    private final Activity context;
    private final String[] items;
    private final String[] prices;
    private final int[] quantities;
    private final Integer[] pictures;

    public CartListAdapter(Activity context, String[] itemnames, String[] prices, int[] quantities, Integer[] pictures) {
        super(context, R.layout.item_list, itemnames);

        this.context=context;
        this.items=itemnames;
        this.prices=prices;
        this.quantities=quantities;
        this.pictures=pictures;
    }

    public View getView(final int position,View view,ViewGroup parent) {
        LayoutInflater inflater=context.getLayoutInflater();
        View rowView=inflater.inflate(R.layout.cart_item, null,true);

        TextView itemName = (TextView) rowView.findViewById(R.id.tvItemName);
        TextView itemPrice = (TextView) rowView.findViewById(R.id.tvPrice);
        ImageView itemPicture = (ImageView) rowView.findViewById(R.id.ivItemPicture);
        View blankView = (View) rowView.findViewById(R.id.blankView);
        Button removeCart = (Button) rowView.findViewById(R.id.btnRemoveCart);

        final Spinner spinner = (Spinner) rowView.findViewById(R.id.spinnerQty);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context, R.array.spinner_numbers, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);


        spinner.setSelection(quantities[position]-1);

        itemName.setText(items[position]);
        itemPrice.setText(prices[position]);
        itemPicture.setImageResource(pictures[position]);

        removeCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ParseUser current = ParseUser.getCurrentUser();
                int quantity = spinner.getSelectedItemPosition()+1;

                Cart userCart = (Cart) current.get("cart");
                boolean success = userCart.removeFromCart(items[position]);

                if(success){
                    Toast.makeText(getContext(), "Removed from Cart", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getContext(), "Item is already in your shopping cart", Toast.LENGTH_LONG).show();
                }

                current.saveInBackground();
            }
        });
        return rowView;
    };
}

我想在用户点击removeCart按钮时更新购物车列表。我怎么能这样做?

更新

我做了一个解决方法,每次删除一个项目时我都会设置一个新的适配器。不是我想做的,但它有效,所以我会保持原样。

3 个答案:

答案 0 :(得分:1)

在自定义适配器中调用this.notifyDataSetChanged();在哪里执行删除功能并从arrayList中删除该元素,该元素设置为该适配器。  如果您知道可以使用哪条记录,则必须从ArrayList中删除已设置为适配器的记录ArrayList.remove(index);然后使用notifyDataSetChanged();

编辑: 转到适配器并添加方法delete();

public void delete(int position){
data.remove(position);
notifyItemRemoved(position);
}

在你的onClick();方法添加:

delete(getPosition());

答案 1 :(得分:1)

试试这个

if (success) {
                    Toast.makeText(getContext(), "Removed from Cart", Toast.LENGTH_LONG).show();
                    final String s = items[position];
                    List<String> list = new ArrayList<String>(Arrays.asList(items));
                    list.remove(s);
                    items = list.toArray(array);
                    this.notifyDataSetChanged()
                }

答案 2 :(得分:0)

这是我的案例中的解决方案。

在CartListAdapter中重写删除阵列适配器的方法。

@Override
public void remove(String var){
    // Call your utility methods you defined to delete the item
    // Notify ListView that their is a change
    notifyDataSetChanged();
}

在Click Listener中进行以下更改

    removeCart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Call this.remove(var) with String you want to delete
        }
    });

notifyDataSetChanged()仅适用于add()insert()remove()clear()的情况。阅读this

HTH