Listview与Checkbox,Textview和按钮在android中无法正常工作?

时间:2012-12-13 08:29:44

标签: java android for-loop

我正在创建一个Android应用程序,我的应用程序的UI在下面给出。 单击提交按钮,我需要选中复选框,值和id textview 未选中示例大小,检查cc(单选按钮)。 记录在列表视图中动态填充,但我无法使其正常工作。

DemoImage Checkbox_ProducoptionActivity.java

 public class MainActivity extends Activity implements OnItemClickListener {

    ListView listview; 
       ArrayList<HashMap<String, String>> list_kategori ;
       ProgressDialog pd;   
       ArrayAdapter<Model_checkbox> adapter;
       List<String> idprdoptins = new ArrayList<String>();  
       List<Model_checkbox> nameprdoptn = new ArrayList<Model_checkbox>(); 
       List<Model_checkbox> list = new ArrayList<Model_checkbox>(); 
       Button btn_checkbox; 
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.checkboxproduct_option);
            listview = (ListView)findViewById(R.id.list); 
            btn_checkbox = (Button)findViewById(R.id.btn_productoption);
            // TODO Auto-generated method stub
            String id =CheckLogin(); 
            if (id!=""){  
                 loadproductoption(id); 
            }  
            btn_checkbox.setOnClickListener(new View.OnClickListener() { 
                public void onClick(View view) {

                    for (Model_checkbox m : list) {
                        Log.i("Stack1", m.toString());
                    }
                     Log.d("Stack1",String.valueOf(Model_checkbox.class));
                    Toast.makeText(getApplicationContext(), "ada",Toast.LENGTH_LONG).show();
                } 
            });
        }  

        public void loadproductoption(String id) {
            listproduct task= new listproduct();
            task.execute(id); 
        }

        private class listproduct extends AsyncTask<String, Void, String>{

             protected void onPreExecute(){
                    pd = new ProgressDialog(Checkbox_ProducoptionActivity.this);
                    pd.setMessage("Please wait..");
                    pd.setCancelable(false);
                    pd.show();
             }

            @Override
            protected String doInBackground(String... params) {
                // TODO Auto-generated method stub
                JSONObject jsonResult   = HttpClientCustom.getRequest(Konfigurasi.strUrl+"api-v1/proop?id_user="+ params[0]);
                return jsonResult.toString();
            } 
            protected void onPostExecute(String result){

                JSONObject jsonResponse=null;
                JSONArray jObject=null;

                 list_kategori = new ArrayList<HashMap<String, String>>();  
                 try {
                        jsonResponse    = new JSONObject(new String(result));  
                        if(jsonResponse.getString("status").equals("SUCCESS")) { 
                            if (!jsonResponse.getString("total").equals("0")){ 
                                jObject         = jsonResponse.getJSONArray("resultset"); 
                                for (int i = 0; i < jObject.length(); i++) {  
                                        HashMap<String, String> map = new HashMap<String, String>(); 
                                        map.put("idprd", jObject.getJSONObject(i).getString("id"));
                                        map.put("id_user", jObject.getJSONObject(i).getString("id_user"));
                                        map.put("namepd", jObject.getJSONObject(i).getString("name"));
                                        setListnama(jObject.getJSONObject(i).getString("name"));
                                        list_kategori.add(map);
                                }    
                                adapter  = new Adapter_Checkboxproductoption(Checkbox_ProducoptionActivity.this, getModel());
                                listview.setAdapter(adapter);
                            }  
                             pd.dismiss();    
                        } else if (jsonResponse.getString("status").equals("FAILED")) {
                            pd.dismiss();     
                        }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }   
                pd.dismiss();    
            }

            private List<Model_checkbox> getModel() { 
                return nameprdoptn;
            } 

            public void setListnama(String name) {
                nameprdoptn.add(new Model_checkbox(name));
            }  
        } 

模型checkbox.java

// public class My modele {

public class Model_checkbox { 

        private String name;
        private boolean selected;
        //private boolean isCcOrIsTo;

        public Model_checkbox(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        } 

        @Override
        public String toString() {
            String selectedString = selected ? "selected" : "not selected";
         //   String value = isCcOrIsTo ? "CC" : "To";
            return name+" -> "+selectedString+ " with value ";
        }
}

MyAdapter.java

// public class MyAdapter extends ArrayAdapter {

class ViewHolder {
    protected TextView text;
    protected CheckBox checkbox; 
}


public class Adapter_Checkboxproductoption extends ArrayAdapter<Model_checkbox> {

        private final List<Model_checkbox> list;
        private final Activity context;
        boolean checkAll_flag = false;
        boolean checkItem_flag = false;

        public Adapter_Checkboxproductoption(Activity context, List<Model_checkbox> list) {
            super(context, R.layout.list_checkbox, list);
            this.context = context;
            this.list = list;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder = null;
            if (convertView == null) {
                LayoutInflater inflator = context.getLayoutInflater();
                convertView = inflator.inflate(R.layout.list_checkbox, null);

                viewHolder = new ViewHolder();
                viewHolder.text = (TextView) convertView.findViewById(R.id.rowTextView);
                viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
                viewHolder.checkbox.setTag(position); 

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.text.setText(list.get(position).getName());
            viewHolder.checkbox.setChecked(list.get(position).isSelected());
            viewHolder.checkbox.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    CheckBox checkbox = (CheckBox) v;
                    int getPosition = (Integer) checkbox.getTag();
                    list.get(getPosition).setSelected(checkbox.isChecked());
                }
            });



            return convertView;
        }
    }

can't work in "Checkbox_ProducoptionActivity.java"
     for (Model_checkbox m : list) {
                        Log.i("Stack1", m.toString());

任何正文都可以帮助我获取所选复选框的值和ID吗?

2 个答案:

答案 0 :(得分:0)

您需要做的就是以这种方式获取/设置适配器中已检查项的值,我在Cursor适配器中可以根据需要更新下面的代码。

public class CursorAdapterList extends CursorAdapter {

    private LayoutInflater inflater = null;
    private DBAdapter db = null;
    private Context ctx = null;

    public CursorAdapterList(Context context, Cursor c, DBAdapter database) {
        super(context, c);
        ctx = context;
        db = database;
        inflater = LayoutInflater.from(context);

    }
    @Override
    public void bindView(View view, Context context, Cursor cursor) {


        TextView tv = (TextView) view.findViewById(R.id.txtGameNameInList);
        CheckBox favBox = (CheckBox) view.findViewById(R.id.favbuttonInList);
        tv.setText(cursor.getString(1));

                //here I am getting value of already checked boxes from db
        String flag = cursor.getString(3);

        if (flag.equals("true")) {
            favBox.setChecked(true);
        } else {
            favBox.setChecked(false);
        }

        favBox.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                LinearLayout parentView = (LinearLayout) v.getParent();
                TextView clickedText = (TextView) parentView
                        .findViewById(R.id.txtGameNameInList);
                                //here you can get the Item value what your selcted in your list
                String name = clickedText.getText().toString();

                if (((CheckBox) v).isChecked()) {
                    Toast.makeText(ctx, name + " is Marked as Favorite Game!!",
                            Toast.LENGTH_SHORT).show();
                                        //below method will store selected item value in db
                    db.markAsFavorite(name, "true");
                } else {
                    db.markAsFavorite(name, "false");
                }

            }

        });



    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return inflater.inflate(R.layout.list_row_custom, parent, false);
    }

}

答案 1 :(得分:-1)

我的活动

public class Checkbox_ProducoptionActivity<country> extends Activity {

        ListView list;
        static Context mContext;
        Button btnSave;  
        List<String> val = new ArrayList<String>();
        ArrayList<HashMap<String, String>> list_kategori ; 
        ArrayList<String> stock_list = new ArrayList<String>();
        ArrayList<String> stock2_list = new ArrayList<String>();
        ProgressDialog pd;   
        EfficientAdapter adapter;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.checkboxproduct_option);
            list = (ListView) findViewById(R.id.ListView01);

            btnSave = (Button)findViewById(R.id.btnSave);
            mContext = this;
             final String id =CheckLogin(); 
             if (id!=""){ 
                 loadproductoption(id);

             }

            btnSave.setOnClickListener(new View.OnClickListener() {  
                public void onClick(View v) {
                    SharedPreferences val_shared = getSharedPreferences("CHECKBOX_SHARED", MODE_WORLD_WRITEABLE);
                    SharedPreferences.Editor cleareditor=val_shared.edit();
                    cleareditor.clear();
                    cleareditor.commit();
                 for (int i = 0; i <list.getCount() ; i++) {
                     View vListSortOrder;
                            vListSortOrder=list.getChildAt(i);     
                            try{
                                TextView textval= (TextView)vListSortOrder.findViewById(R.id.TextView01);
                                CheckBox ckc=(CheckBox)vListSortOrder.findViewById(R.id.chkbox1);
                                EditText edit=(EditText)vListSortOrder.findViewById(R.id.txtbox);
                                if (ckc.isChecked()){
                                      edit.getText().toString();
                                      String temp1 = textval.getText().toString();
                                      Toast.makeText(getApplicationContext(), "fuck"+textval.getText().toString(), Toast.LENGTH_LONG).show();
                                      val.add(temp1);
                                }   
                            }catch (Exception e) {
                                // TODO: handle exception
                            }
                    }
                SharedPreferences customer_ident = getSharedPreferences("CHECKBOX_SHARED", MODE_WORLD_WRITEABLE);
                SharedPreferences.Editor editor=customer_ident.edit(); 
                editor.putString("valuecheck", val.toString()); 
                editor.commit();
              //  Toast.makeText(getApplicationContext(), "ada "+val, Toast.LENGTH_LONG).show();
                Intent prdmenuact = new Intent(getApplicationContext(),CreateManageProductActivity.class);
                prdmenuact.putExtra("idaction", "1"); 
                startActivity(prdmenuact);
                finish();
            } 
            }); 
    }

    public void loadproductoption(String id) {
        listproduct task= new listproduct();
        task.execute(id); 
    } 

    private class listproduct extends AsyncTask<String, Void, String>{

         protected void onPreExecute(){
                pd = new ProgressDialog(Checkbox_ProducoptionActivity.this);
                pd.setMessage("Please wait..");
                pd.setCancelable(false);
                pd.show();
         }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            JSONObject jsonResult   = HttpClientCustom.getRequest(Konfigurasi.strUrl+"api-v1/proop?id_user="+ params[0]);
            return jsonResult.toString();
        } 
        protected void onPostExecute(String result){

            JSONObject jsonResponse=null; 
            JSONArray jObject=null;

             list_kategori = new ArrayList<HashMap<String, String>>();  
             try {
                    jsonResponse    = new JSONObject(new String(result));  
                    if(jsonResponse.getString("status").equals("SUCCESS")) { 
                        if (!jsonResponse.getString("total").equals("0")){ 
                            jObject         = jsonResponse.getJSONArray("resultset"); 
                            for (int i = 0; i < jObject.length(); i++) {  
                                    HashMap<String, String> map = new HashMap<String, String>(); 
                                    map.put("idprd", jObject.getJSONObject(i).getString("id"));
                                    map.put("id_user", jObject.getJSONObject(i).getString("id_user"));
                                    map.put("namepd", jObject.getJSONObject(i).getString("name")); 
                                    list_kategori.add(map);   
                            }  
                            adapter = new  EfficientAdapter(Checkbox_ProducoptionActivity.this,list_kategori );
                            list.setAdapter(adapter); 
                        }  
                         pd.dismiss();    
                    } else if (jsonResponse.getString("status").equals("FAILED")) {
                        pd.dismiss();     
                    }
            } catch (JSONException e) {
             //TODO Auto-generated catch block
                e.printStackTrace();
            }   
            pd.dismiss();    
        } 
    }

我的适配器

public class EfficientAdapter extends BaseAdapter { 

        private Activity activity;
        private ArrayList<HashMap<String, String>> data;
        private  LayoutInflater inflater=null;
        public ImageLoader imageLoader; 
        String priceprd ;

        public EfficientAdapter (Activity a, ArrayList<HashMap<String, String>> d) {
            activity = a;
            data=d;
            inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            imageLoader=new ImageLoader(activity.getApplicationContext());
        }

        public EfficientAdapter(Runnable runnable,
                ArrayList<HashMap<String, String>> list_kategori) {
            // TODO Auto-generated constructor stub
        }

        public int getCount() {
            //Log.d("country",String.valueOf(data.size()));
            return data.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.list_checkbox, parent,
                        false);
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.TextView01);
                holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);
                holder.txt = (EditText) convertView.findViewById(R.id.txtbox);
                holder.cbox = (CheckBox) convertView.findViewById(R.id.chkbox1);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            } 
            holder.text.setText( data.get(position).get("idprd"));
            holder.text2.setText(data.get(position).get("namepd"));
            holder.txt.setText("");
            holder.cbox.setChecked(false); 
            return convertView;
        }

        public class ViewHolder {
            TextView text;
            TextView text2;
            EditText txt;
            CheckBox cbox;
        }
    }


public String[] convert(List<String[]> list1) {
        // TODO Auto-generated method stub
        return null;
    }

要更换的适配器 并删除了模型 所以要检查一下使用缺血的价值

for (int i = 0; i <list.getCount() ; i++) {
                     View vListSortOrder;
                            vListSortOrder=list.getChildAt(i);     
                            try{
                                TextView textval= (TextView)vListSortOrder.findViewById(R.id.TextView01);
                                CheckBox ckc=(CheckBox)vListSortOrder.findViewById(R.id.chkbox1);
                                EditText edit=(EditText)vListSortOrder.findViewById(R.id.txtbox);
                                if (ckc.isChecked()){
                                      edit.getText().toString();
                                      String temp1 = textval.getText().toString();
                                      Toast.makeText(getApplicationContext(), "fuck"+textval.getText().toString(), Toast.LENGTH_LONG).show();
                                      val.add(temp1);
                                }   
                            }catch (Exception e) {
                                // TODO: handle exception
                            }
                    }

并成功