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?
Previous answers are correct, telling you don't call the show() method of the Toast. You can also take a look at this tutorial to see how you can define a handler method to your button in the XML. This way the code will look clearer, because you don't have to explicitly implement onClickListener interface, or set new onClickListener to a button (it's done behind the scenes). Here's a simple example (you can easily supplement the System prints with "showToast" methods):
button definition in xml:
Activity class
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
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).
You need to call
show()
for the toast to appear :Add this in your java resource
Then this code for adding a button and implementing it to display the toast message in your XML resource.
Hope this helped. Happy Coding
you just forgot to add .show() after your .makeText(context,text,duration)
so your code should like this: