Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

android - how to update the textview text depending on the state of a checkbox in listview

Here is My Custom ListViewAdapter

public class ListViewAdapter extends BaseAdapter{


    Viewholder holder;
    public ArrayList<HashMap<?, ?>>list;
    public ArrayList<Integer> add;
    Activity activity;
    boolean [] checkedItems;

    String []ckboxTextAdd;
    DbAdapter db;
    /*
     * Constructor Calling
     */

    public ListViewAdapter(Activity activity,ArrayList<HashMap<? , ?>>list) {
        // TODO Auto-generated constructor stub
         super();
         this.activity=activity;
         this.list=list;
         add=new ArrayList<Integer>(list.size());
         db=new DbAdapter(activity);
         db.open();
         checkedItems= new boolean[list.size()];

         ckboxTextAdd=new String[list.size()];
         for(int i=0;i<list.size();i++)
         {
             checkedItems[i]=false;
             ckboxTextAdd[i]="Add";

         }

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(final int position, View convertview, ViewGroup parent) {
        // TODO Auto-generated method stub

        LayoutInflater layoutInflater=activity.getLayoutInflater();
        final HashMap<?, ?> map=list.get(position);
        if(convertview==null)
        {
        convertview=layoutInflater.inflate(R.layout.l_view,parent,false);
        holder = new Viewholder();
        holder.title=(TextView) convertview.findViewById(R.id.serving_size_grams);
        holder.servingsize=(TextView) convertview.findViewById(R.id.tvprotiendesclabel);
        holder.Fiber=(TextView)convertview.findViewById(R.id.Fiberview);

        holder.carbs=(TextView)convertview.findViewById(R.id.carbsview);
        holder.sodium=(TextView)convertview.findViewById(R.id.sodiumview);
        holder.proteins=(TextView)convertview.findViewById(R.id.Protienview);
        holder.calories=(TextView)convertview.findViewById(R.id.caloriesview);
        holder.img_serve_size=(ImageView)convertview.findViewById(R.id.image_serve_eqivalent);

        holder.calories_val=(TextView)convertview.findViewById(R.id.cal_desc_val);
        holder.Fiber_val=(TextView)convertview.findViewById(R.id.Fiber_desc_val);
        holder.sodium_val=(TextView)convertview.findViewById(R.id.sodium_desc_val);
        holder.proteins_val=(TextView)convertview.findViewById(R.id.prot_desc_val);
        holder.carbs_val=(TextView)convertview.findViewById(R.id.carbs_desc_val);
        holder.tvbrand=(TextView)convertview.findViewById(R.id.item_brand_name);
        holder.ckbox=(CheckBox)convertview.findViewById(R.id.save_item_box);
        holder.tvckboxText=(TextView)convertview.findViewById(R.id.ckboxAdd);



        convertview.setTag(holder);
        }   
         else
         {
              holder=(Viewholder)convertview.getTag();
         }


         holder.ckbox.setOnCheckedChangeListener(null);
         holder.ckbox.setChecked(checkedItems[position]);
         holder.tvckboxText.setText(ckboxTextAdd[position]);
         holder.ckbox.setTag(R.id.save_item_box, position);
        //On Check Box Check Events



         holder.ckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {



             @Override
                public void onCheckedChanged(final CompoundButton buttonview, boolean isChecked) {
                    // TODO Auto-generated method stub

                     final int position = (Integer) buttonview
                                .getTag(R.id.save_item_box);

                       if (isChecked) 
                       {
                           Log.i(String.valueOf(position), String.valueOf(isChecked));


                          checkedItems[position] = true;
                          ckboxTextAdd[position]="Added";

                         //holder.ckbox.setText(ckboxTextAdd[position]);
                         Log.i("value of Somple List", list.get(position).toString());
                         Log.i("value of listitr", list.get(position).toString());
                         Log.i("value of text box",ckboxTextAdd[position]);
                         final HashMap<?, ?> map=list.get(position);
                         map.get(Constants.NF_CALORIES);

                         String item_name =map.get(Constants.ITEM_NAME).toString().replace(''', ' ');
                         String brand_name =map.get(Constants.BRAND_NAME).toString().replace(''',' ');
                         Cursor cursor= db.fetch_data(item_name,brand_name);
                         if(cursor.getCount()>0)
                        {
                             AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                             builder.setMessage("Already Saved")
                                    .setPositiveButton("Replace", new DialogInterface.OnClickListener() 
                                    {
                                        public void onClick(DialogInterface dialog, int id)
                                        {

                                                        checkedItems[position] = true;
                                                        ckboxTextAdd[position]="Added";

                                                        Log.i("value of text box trey",ckboxTextAdd[position]);
                                                        //   holder.ckbox.setText(ckboxTextAdd[position]);
                                         }
                                    })
                                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
                                    {
                                        public void onClick(DialogInterface dialog, int id) 
                                        {


                                            checkedItems[position] = false;
                                            ckboxTextAdd[position]="Add";

                                               Log.i("value of text box false",ckboxTextAdd[position]);
                                            //holder.ckbox.setText(ckboxTextAdd[position]);

                                         }
                                    });

                             AlertDialog alertDialog = builder.create();
                             alertDialog.show();
                        }
                        else
                            {


                            Log.i("value of Calories",map.get(Constants.NF_CALORIES).toString());
                            db.createSave(
                                  position
                                  ,brand_name
                                  ,item_name
                                  ,map.get("path").toString()
                                  ,map.get(Constants.NF_SERVING_SIZE_QTY).toString()
                                  ,map.get(Constants.NF_SERVING_SIZE_UNIT).toString()
                                  ,map.get(Constants.NF_CALORIES).toString()
                                  ,map.get(Constants.NF_PROTEINS).toString()
                                  ,map.get(Constants.NF_SODIUM).toString()
                                  ,map.get(Constants.NF_TOTAL_FAT).toString()
                                  ,map.get(Constants.NF_TOTAL_CARBOHYDRATES).toString()
                                  ,map.get(Constants.NF_SATURATED_FAT).toString()
                                  ,map.get(Constants.NF_CHOLESTEROL).toString()
                                  ,map.get(Constants.NF_VITAMIN_A).toString()
                                  ,map.get(Constants.NF_VITAMIN_C).toString()
                                  ,map.get(Constants.NF_IRON).toString()
                                  ,map.get(Constants.NF_CALCIUM).toString()
                                  ,map.get(Constants.NF_SERVING_WEIGHT_GRAMS).toString()
                                  );
                            }
                        }
                       else 
                        {
                            Log.i(String.valueOf(position), String.valueOf(isChecked));
                            //buttonview.setChecked(false);
                            //buttonview.setText("Save");
                             ckboxTextAdd[position]="Add";

                               Log.i("value of text box false",ckboxTextAdd[position]);
                        //   holder.ckbox.setText(ckboxTextAdd[position]);
//                          holder.ckbox.setText("Save");
//                          holder.ckbox.setBackgroundColor(Color.rgb(198, 228, 225));
                            checkedItems[position] = false;
                            //holder.ckbox.setText(ckboxTextAdd[position]);
                            db.deleteUnChecked(position);
                        }
                }
            });
}
        return convertview;
    }
private class Viewholder extends Activity
    {
        TextView title;
        TextView servingsize;
        //TextView status;
        TextView carbs;
        TextView proteins;
        TextView calories;
        ImageView img_serve_size;
        TextView sodium;
        TextView Fiber;

        TextView carbs_val;
        TextView proteins_val;
        TextView calories_val;
        TextView sodium_val;
        TextView Fiber_val;
        CheckBox ckbox;
        TextView tvbrand;


        TextView tvckboxText;
    }

Now what i wants to update my textview at the instant the checkbox is clicked in the listview but till now it doest not do as desired but when i scroll down and take alook on the checked item then the textView is Updated

Please help me Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Problem:

When you're updating the values of array to map the status of checked or un-checked, you're not updating the TextView, as CheckBox's check or uncheck works out-of-box as implemented the api, but TextView's text need to be updated.

Solution:

You need to either manually update the TextView's text, or simply call notifyDataSetChanged() whenever you check or uncheck the item, this will let the getView() of Adapter called and will force to refresh the row based on updated value.

Suggestion/Improvement:

  1. You can maintain single array of boolean only, no need to maintain the String array of Added or Add, while showing text, check if the boolean is true, set text as "Added", else "Add" like this:

    holder.ckbox.setChecked(checkedItems[position]);
    holder.tvckboxText.setText(checkedItems[position]?"Added":"Add");
    
  2. Instead of implementing anonymous CompoundButton.OnCheckedChangeListener, implement it to class level and set as this, as of now you're creating multiple CompoundButton.OnCheckedChangeListener object every time when you scroll through the list.

  3. Where are you closing the db? It doesn't matter though, but its good to have a closing point.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...