java - 自定义 ListView 中的复选框

标签 java android

这是我的 ListActivity,其中包含我想在 AddOrder Activity 中传递的各种菜肴:

    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 类中创建了 boolean 值复选框 - 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;
}

}

但是当我单击“继续”按钮 checked.size() 时,它给出 null 值,并且我的数据不会传递到第二个 Activity。

最佳答案

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

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);
    }
}

关于java - 自定义 ListView 中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28264984/

相关文章:

java - java中的静态初始化

java - 如何在MySQL上插入Java数据

android - Firebase 不发送 OTP

java - 具有泛型的 gson 的正确语法

android - RelativeLayout 中的另一个中心 View

java - 有没有办法更改上下文操作栏的背景颜色?

java - org.hibernate.InstantiationException : Cannot instantiate abstract class or interface: device. 处置

java - Spring 批处理 : How to set up a job repository for every job

java - 写入数组中的元素

java - 如何获取谷歌地图v2中标记的经度和纬度值