jeudi 26 mai 2016

Get value from CheckBox in custom ListView

Well I have implemendes a HashMap where the key is a String and the value is a Integer the thing is that I'd like to know how could I get the value of the radio button clicked, to get the value, and then if I could do some operations with them, for example:

Cb1 2 Checked

Cb2 9 Checked

Cb3 19 UnChecked

The output should be 11 (2+9)

So I'd like to make a sum of checked ones and update a TextView with that value.

From now I have this :

This is the HashMap

HashMap<String, Integer> hmAs = new LinkedHashMap<String, Integer>();

And this is how I create the Dialog

Dialog mDialog;
mDialog=new Dialog(this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setContentView(R.layout.custom_dialog_as);
ListView lv = (ListView) mDialog.findViewById(R.id.listView);
Button bt = (Button) mDialog.findViewById(R.id.btAcceptAs);
    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mDialog.dismiss();
                       //Here I need the sum of all of the values
        }
    });
ArrayAdapter adapter = new HashMapArrayAdapter(this, android.R.layout.simple_list_item_single_choice, new ArrayList(hmAs.entrySet()));
lv.setAdapter(adapter);
mDialog.show();

And this is the Adapter

class HashMapArrayAdapter extends ArrayAdapter {

Context mContext;

private static class ViewHolder {
    TextView tV1;
    CheckBox cb;
}

public HashMapArrayAdapter(Context context, int textViewResourceId, List<Map.Entry<String, Integer>> objects) {
    super(context, textViewResourceId, objects);
    this.mContext = context;
}

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

    ViewHolder viewHolder;

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.custom_item_dialog, parent, false);
        viewHolder = new ViewHolder();
        viewHolder.tV1 = (TextView) convertView.findViewById(R.id.tvDataAs);
        viewHolder.cb = (Checkbox) convertView.findViewById(R.id.checkbox);
        convertView.setTag(viewHolder);
    } else
        viewHolder = (ViewHolder) convertView.getTag();

    Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) this.getItem(position);

    viewHolder.tV1.setText(entry.getKey());
    viewHolder.rb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Toast.makeText(mContext, String.valueOf(entry.getValue()), Toast.LENGTH_SHORT).show();
        }
    });

    return convertView;
}
}

With this Toast I get the exact value of the map but the problem is how from the dialog, that I have the Button when I press "Accept" I can get the sum of all of the CheckBox of the ListView




Aucun commentaire:

Enregistrer un commentaire