当在android中以编程方式进行复选框时,如何从复选框中选中复选框复选框值

时间:2014-06-19 11:28:02

标签: java android checkbox android-checkbox

我正在以编程方式制作复选框。并且我想在点击按钮时获得已检查复选框的价值...我该怎么做....

我从数据库中获得了复选框的价值。

这是我的工作代码..

        public class Loyaltyprogram extends Activity {          
        SessionManager session;
        EditText mpv, discount;
        Button save;

        String finalresult, getFlag, statusEmp, accessName, emp_id, bus_id,
                preferences, bus_type_id, emp_access_name, responseString, success,
                name, id, pref, per_amout, percentage, datediff, dateNo, minpvalue , discountonit;
        Toast tag;
        // flag for Internet connection status
        Boolean isInternetPresent = false;
        // Connection detector class
        ConnectionDetector cd;
        ProgressDialog pDialog;
        int a;
        String[] idsplit, namesplit, prefsplit;
        List<String> testArrayList;
        LinearLayout llmain;
        LinearLayout[] lLayout;
        Integer count1 = 0;
        Context mContext;
        TextView tvo;
        CheckBox cb;
        StringBuffer result = new StringBuffer();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.loyaltyprogram);

            tvo = (TextView) findViewById(R.id.tvother);
            mpv = (EditText) findViewById(R.id.et_minpurchase);
            discount = (EditText) findViewById(R.id.et_discount);

            isInternetPresent = cd.isConnectingToInternet();
            if (isInternetPresent) {
                new Homedatanew().execute();
                llmain = (LinearLayout) findViewById(R.id.linearLayoutMain);
            } else {
                Toast toast = Toast.makeText(getApplicationContext(),
                        "Check your internet connection", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }

            save = (Button) findViewById(R.id.button);
            save.setOnClickListener(new OnClickListener() {

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

                    minpvalue = mpv.getText().toString();
                    discountonit = discount.getText().toString();

                    for(int t = 0; t<idsplit.length; t++)
                    {
                        if(cb.isChecked())
                        {
                            System.out.println(idsplit[t]);
                        }
                    }               
                }
            });
        }

        class Homedatanew extends AsyncTask<String, String, String> {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(Loyaltyprogram.this);
                pDialog.setMessage("loading data..");
                pDialog.setCancelable(false);
                pDialog.show();
            }

            protected String doInBackground(String... params) {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        "http://10.0.2.2/amardeep/android_api/checkbox.php");
                try {
                    session = new SessionManager(getApplicationContext());
                    // get user data from session
                    HashMap<String, String> user = session.getUserDetails();
                    // id
                    bus_id = user.get(SessionManager.KEY_B_ID);
                    bus_type_id = user.get(SessionManager.KEY_B_TYPE_ID);
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                            2);
                    nameValuePairs.add(new BasicNameValuePair("bus_type_id",
                            "BT101"));
                    nameValuePairs.add(new BasicNameValuePair("bus_id", "B101"));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    response.getStatusLine().getStatusCode();
                    HttpEntity getResponseEntity = response.getEntity();
                    responseString = EntityUtils.toString(getResponseEntity);
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                }
                return responseString;
            }

            @SuppressLint("NewApi")
            protected void onPostExecute(String resultStr) {
                try {
                    JSONObject json = new JSONObject(responseString);
                    JSONArray jArray = json.getJSONArray("customer");
                    for (int i = 0; i < jArray.length(); i++) {
                        JSONObject json_data = jArray.getJSONObject(i);
                        success = json_data.getString("success");
                        id = json_data.getString("id");
                        name = json_data.getString("name");
                        pref = json_data.getString("pref");
                        per_amout = json_data.getString("per_amount");
                        percentage = json_data.getString("percentage");
                        datediff = json_data.getString("dateDiff");
                        dateNo = json_data.getString("dateNo");
                        if (percentage.equals("null")) {
                            percentage = "";
                        }
                        if (per_amout.equals("null")) {
                            per_amout = "";
                        }
                        if((datediff.equals("No"))&&(dateNo.equals("No")))
                        {
                            count1 = 1;
                        }
                        else if((datediff.equals("YES"))&&(dateNo.equals("No")))
                        {
                            count1 = 2;
                        }
                        else
                        {
                            count1 = 0;
                        }

                        idsplit = id.split(",");
                        a = idsplit.length;
                        namesplit = name.split(",");
                        prefsplit = pref.split(",");
                        testArrayList = new ArrayList<String>(
                                Arrays.asList(prefsplit));
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (success.equals("1")) {
                    mpv.setText(per_amout);
                    discount.setText(percentage);
                    if ((count1.equals(1)) || (count1.equals(2))) {
                        mpv.setEnabled(true);
                        discount.setEnabled(true);
                    } else {
                        mpv.setEnabled(false);
                        discount.setEnabled(false);
                        save.setEnabled(false);
                    }
                    int b = (a / 5);
                    int c = (a % 5);
                    if (c != 0) {
                        b = b + 1;
                    }
                    lLayout = new LinearLayout[b];
                    for (int j = 0; j < b; j++) {
                        int x = 0;
                        x = x + (j * 5);
                        lLayout[j] = new LinearLayout(Loyaltyprogram.this);
                        lLayout[j].setLayoutParams(new LayoutParams(
                                LayoutParams.WRAP_CONTENT,
                                LayoutParams.WRAP_CONTENT));
                        lLayout[j].setOrientation(LinearLayout.VERTICAL);
                        llmain.addView(lLayout[j]);
                        for (int i = x; i < x + 5; i++) {
                            if (x > a) {
                                break;
                            } else {
                                if (testArrayList.contains(idsplit[i])) {
                                    cb = new CheckBox(Loyaltyprogram.this);
                                    cb.setText(namesplit[i] + (i + 1));
                                    cb.setId(i + 1);
                                    cb.setChecked(true);
                                    cb.setTextColor(Color.BLACK);
                                    cb.setTextSize(12f);
                                    cb.setButtonDrawable(R.drawable.checkbox);
                                    cb.setPadding(35, 5, 25, 5);
                                    if (count1.equals(1)) {
                                        cb.setEnabled(true);
                                    } else {
                                        cb.setEnabled(false);
                                    }
                                    lLayout[j].addView(cb);
                                } else {
                                    cb = new CheckBox(Loyaltyprogram.this);
                                    cb.setText(namesplit[i] + (i + 1));
                                    cb.setId(i + 1);
                                    cb.setTextColor(Color.BLACK);
                                    cb.setTextSize(12f);
                                    cb.setButtonDrawable(R.drawable.checkbox);
                                    cb.setPadding(35, 5, 25, 5);
                                    if (count1.equals(1)) {
                                        cb.setEnabled(true);
                                    } else {
                                        cb.setEnabled(false);                                   
                                    }
                                    lLayout[j].addView(cb);
                                }
                            }                       
                        }
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "data empty",
                            Toast.LENGTH_LONG).show();
                    mpv.setEnabled(true);
                    discount.setEnabled(true);
                }
                pDialog.dismiss();
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

只需在循环中执行此操作,否则执行条件

cb.setTag(i+99); // set the tag values so that you can refer to them later.

cb.setOnCheckedChangeListener(handleCheck(cb)); // here pass the checkbox object.

然后这是handleCheck方法

private OnCheckedChangeListener handleCheck (final CheckBox chk)
    {
        return new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if(!isChecked){                           
                   Toast.makeText(getApplicationContext(), "You unchecked " + chk.getTag(),
                        Toast.LENGTH_LONG).show();
                }
                else
                {   
                    Toast.makeText(getApplicationContext(), "You checked " + chk.getTag(),
                        Toast.LENGTH_LONG).show(); 
                }
            }
        };
    }

希望这会给你一些想法。快乐的编码:)