mardi 29 août 2017

how do i create a toast that reads off the checked check boxes in a list with an adapter

ive created a list using a custom adapter the list has checkboxes and i have a button at the bottom of the main activity. what im hoping to achieve is that when i press the button a toast will appear stating all the items that have been checked.i know i need to create a list array but im not sure how to use the checked checkboxes into deciphering what goes into the array list. thanks for any help will be much appreciated. heres the java code ive got so far.

public class MainActivity extends AppCompatActivity {
ListView lv;
boolean [] checkBoxes;
int boxIndex = 0;
Button b;

@Override
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.activity_main);
    String[] s = {"Ham and pineapple", "Supreme", "Seafood",
            "Italian", "Meat lovers", "cheese"};
    checkBoxes = new boolean[s.length];


    CustomAdapter adapter = new CustomAdapter(this, s);
    lv = (ListView) findViewById(R.id.listView);
    b = (Button) findViewById(R.id.button);
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
           String item = (String)lv.getAdapter().getItem(position);
          Toast.makeText(getApplicationContext(), item + " is selected", Toast.LENGTH_LONG).show();

          CheckBox cb = (CheckBox) lv.findViewById(R.id.checkBox);
          boxIndex = position;
          cb.setOnClickListener(new View.OnClickListener() {
              public void onClick(View view) {
                  checkBoxes[boxIndex] = true;
              }
          });

      }

  });

public static class CustomAdapter extends ArrayAdapter<String>
{
   private final Context context;
    private final String[] s;

    public CustomAdapter(Context context, String[] s) {
        super(context, R.layout.rowlayout, s);
        this.context = context;
        this.s = s;
    }
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.rowlayout, parent, false);

        TextView textView = (TextView) rowView.findViewById(R.id.list_item);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
        textView.setText(s[position]);
        String t = s[position];
        if (t.startsWith("Supreme") || t.startsWith("Seafood")) {
            imageView.setImageResource(R.drawable.star);
        } else {
            imageView.setImageResource(R.drawable.pizza);
        }

        return rowView;
    }
  }
}




Aucun commentaire:

Enregistrer un commentaire