Search code examples
androidbuttontoast

Android: Have toast appear on button click


I'm fairly new to Android and just getting familiarized with the common stuff, but I can't get the hang of the onClickListner(); I basically have two checkboxes and a button and on button click a toast should show up and say which checkboxes are checked and which aren't.

public class ExActivity extends Activity implements View.OnClickListener {
    CheckBox cb;
    CheckBox cb2;
    Button buton;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        cb=(CheckBox) findViewById(R.id.cb);
        cb2=(CheckBox) findViewById(R.id.checkbox);
        buton = (Button)findViewById(R.id.buton);
        buton.setOnClickListener(this);
    }

    public void onClick(View arg0) {
        Toast toast;
        if(cb.isChecked()&&cb2.isChecked()) toast = Toast.makeText(getApplicationContext(), "Amandoua sunt bifate", Toast.LENGTH_SHORT);
        else if(cb.isChecked()&&!cb2.isChecked()) toast = Toast.makeText(getApplicationContext(), "Doar prima e bifata", Toast.LENGTH_SHORT);
        else if(!cb.isChecked()&&cb2.isChecked()) toast = Toast.makeText(getApplicationContext(), "Doar a doua e bifata", Toast.LENGTH_SHORT);
        else if(!cb.isChecked()&&!cb2.isChecked()) toast = Toast.makeText(getApplicationContext(), "Nici una nu e bifata", Toast.LENGTH_SHORT);
    }
}

Disregard the romanian variable names and texts and the XML is all right. I also tried to add the onClick() like this:

buton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // my code;
    }
});

but this one is even worse. Help?


Solution

  • Both ways are correct. It seems to me that you just didn't show the toast in the end. Which can look like the onClick wasn't executed.

    Adding

    if(toast != null) {
        toast.show();
    }
    

    to the end of your onClick() method should do the trick.
    (The null check just in case you didn't create a toast instance because no condition was matched before).