自定义列表中的复选框VIew

时间:2015-02-01 16:33:29

标签: java android

这是我的ListActivity,其中包含我希望在AddOrder活动中传递的各种菜肴:

    public class MainActivity extends ListActivity {

    ListView list;
    Button btn1;
    String url="";
    private ArrayList <Product>  allProducts = new ArrayList<Product>();
    private ProductAdapter adapter;

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

        btn1 = (Button) findViewById(R.id.btn);
        list = getListView();
    //  list = (ListView)findViewById(R.id.list);
        //Bundle d = getIntent().getExtras();

        url="http://192.168.1.100/test/product.txt?id=";//+d.getInt("id");

        try{
            ConnectivityManager c =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);                  
            NetworkInfo n =c.getActiveNetworkInfo();
            if (n!= null && n.isConnected()){
                Log.d("url*********",url);

                new Background().execute(url);
            }
           }catch(Exception e){}

        //Toast.makeText(getApplicationContext(), url, Toast.LENGTH_LONG).show();

    adapter = new ProductAdapter(getApplicationContext(),R.layout.productrow,allProducts);

    setListAdapter(adapter);

    //list.setItemsCanFocus(false);

     btn1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stu lib

        SparseBooleanArray checked = list.getCheckedItemPositions();

        ArrayList<String> selectedItems = new ArrayList<String>();
        ArrayList<Integer> selectedItemsPrice = new ArrayList<Integer>();
        ArrayList<Integer> selectedItemsId = new ArrayList<Integer>();
      // Log.d("**************",Integer.toString(checked.size()));

        if(checked!=null){
        for (int i = 0; i < checked.size(); i++) {
            // Item position in adapter
            int position = checked.keyAt(i);
            // Add sport if it is checked i.e.) == TRUE!
            if (checked.valueAt(i))
                {
                selectedItems.add(adapter.getItem(position).getProduct_name());
                selectedItemsPrice.add(adapter.getItem(position).getProduct_price());
                selectedItemsId.add(adapter.getItem(position).getProduct_id());
                }
        }}

        int k = selectedItems.size();
        int[] outputStrArrId = new int[k];
        int[] outputStrArrPrice = new int[k];
        String[] outputStrArrItem = new String[k];

        for (int i = 0; i < k; i++) {
            outputStrArrItem[i] = selectedItems.get(i);
            outputStrArrId[i] = selectedItemsId.get(i);
            outputStrArrPrice[i] = selectedItemsPrice.get(i);
        }

        Intent intent = new Intent(getApplicationContext(), AddOrder.class);

        // Create a bundle object
        Bundle b = new Bundle();
        b.putStringArray("st3", outputStrArrItem);

        b.putIntArray("st1",outputStrArrId );
        b.putIntArray("st2",outputStrArrPrice );
        // Add the bundle to the intent.
        intent.putExtras(b);

        // start the ResultActivity
        startActivity(intent);

    }
    });


    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);

        Product p = allProducts.get(position);
        if(p.isChecked() == true) 
        p.setChecked(false);
        else
            p.setChecked(true);

    }

    class Background extends AsyncTask<String,Void,Boolean>
    {
        ProgressDialog dialog;

        String check = "";
        int count=0;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading, please wait");
            dialog.setTitle("Connecting server");
            dialog.show();
            dialog.setCancelable(false);


            //DisplayToast("Calling Background");

        }

        @Override
        protected Boolean doInBackground(String... arg0) {
            // TODO Auto-generated method stub

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpget = new HttpPost(arg0[0]);
            HttpResponse response;
        //  Log.d("url",arg0[0]);
            try{

                response = httpclient.execute(httpget);

                if(response!=null)
                {
                    //My Logic

                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);

                    JSONObject jsono = new JSONObject(data);
                    JSONArray jarray = jsono.getJSONArray("Products");

                    int count = 0;

                    for (int i = 0; i < jarray.length(); i++) {
                        JSONObject object = jarray.getJSONObject(i);

                        Product d = new Product();
            d.setHotel_id(Integer.parseInt(object.getString("hotel_id")));
        d.setProduct_id(Integer.parseInt(object.getString("product_id")));
                        d.setProduct_name(object.getString("product_name"));
    d.setProduct_price(Integer.parseInt(object.getString("product_price")));
                        if(object.has("product_qunatity"))
                            d.setProduct_qunatity(Integer.parseInt(object.getString("product_qunatity")));

                        Log.d("do in backgroung",Integer.toString(count++));
                        allProducts.add(d);

                    //  Log.d("do in backgroung",Integer.toString(count++));
                    }
                    return true;

                }

            } catch(Exception e)
            {
                Log.d("---////////////---", e.toString());
            }

            return false;
        }

        public void onPostExecute(Boolean result)
        {
            dialog.cancel();
            adapter.notifyDataSetChanged();
            if(result == false)
                Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();

        }
    }

    private void DisplayToast(String msg)
    {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();

    }

   }

我的自定义适配器是ProductAdapter.java

public class ProductAdapter extends ArrayAdapter<Product> {
private ArrayList<Boolean> itemChecked      = null;
ArrayList<Product> allProducts;
LayoutInflater vi;
int Resource;
ViewHolder holder;


public ProductAdapter (Context context , int resource ,ArrayList<Product> objects)
{
    super(context, resource, objects);
    vi = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Resource = resource;
    allProducts = objects;

}
@Override
public View getView(int position ,View convertView,ViewGroup parent)
{
    View v = convertView;
    if(v==null)
    {
        holder = new ViewHolder();
        v = vi.inflate(Resource, null);

        holder.name = (TextView) v.findViewById(R.id.tv1);
        holder.price = (TextView) v.findViewById(R.id.price);
        holder.checkbox = (CheckBox) v.findViewById(R.id.cb1);

        v.setTag(holder);

    }

    else{
        holder = (ViewHolder) v.getTag();

    }

    //holder.imageview.setImageResource(R.drawable.ic_launcher);
    holder.name.setText(allProducts.get(position).getProduct_name());

    int s = allProducts.get(position).getProduct_price();
    //Log.d("********************",Integer.toString(s));
    holder.price.setText(Integer.toString(s));

    //final ListView lv = (ListView) parent;
    //holder.checkbox.setChecked(lv.isItemChecked(position));

    holder.checkbox.setChecked(allProducts.get(position).isChecked());

    return v;

}

static class ViewHolder {
    public TextView name;
    public TextView price;
    public CheckBox checkbox ;
}

 }

我还在pojo类中创建了布尔值复选框 - Product.java

public class Product {

int product_id;

private boolean checked = false ;

    public boolean isChecked() {
    return checked;
}

public void setChecked(boolean checked) {
    this.checked = checked;
}

    String product_name;

   int product_price;

   int product_qunatity;

   int hotel_id;

public int getProduct_id() {
    return product_id;
}

public void setProduct_id(int product_id) {
    this.product_id = product_id;
}

public String getProduct_name() {
    return product_name;
}

public void setProduct_name(String product_name) {
    this.product_name = product_name;
}

public int getProduct_price() {
    return product_price;
}

public void setProduct_price(int product_price) {
    this.product_price = product_price;
}

public int getProduct_qunatity() {
    return product_qunatity;
}

public void setProduct_qunatity(int product_qunatity) {
    this.product_qunatity = product_qunatity;
}

public int getHotel_id() {
    return hotel_id;
}

public void setHotel_id(int hotel_id) {
    this.hotel_id = hotel_id;
}

}

但是当我点击Proceed按钮checked.size()时,它会给出null值,而我的数据不会传递给第二个Activity。

1 个答案:

答案 0 :(得分:0)

首先,在ListView方法中将onCreate()的选择模式设置为 multiple

getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

然后在onListItemClick()方法中,您还需要将列表项标记为已选中。

protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);

    Product p = allProducts.get(position);
    if (p.isChecked()) { 
        p.setChecked(false);
        l.setItemChecked(position, false);
    } else {
        p.setChecked(true);
        l.setItemChecked(position, true);
    }
}