Android's toast is a little popup message that fades in and out as we call it. We can control it's fade time and some other features as indicated on the developer page but that isn't what we are focusing on here. We are focused on actually getting one to display after a button has been clicked. Toast is a view.
The first thing we need to do is add a button to our layout. Select the XML file from the folder tree on the left (in the Package Explorer) and double click (open) the XML file.
The file should load in the pane on the right hand side. If this is a new project delete the default text that comes with it. If you delete the text here be sure to delete it from the app_strings also. Not deleting it from app_strings won't damage the application but it's nice to keep it clean. Click and drag the button onto the form.
Now change the width so it's not so ugly.
Now that our button's name is button1. We are going to add another library to reference at the top witht he rest that will give us access to use the OnClickListener event handler.
import android.view.View; import android.widget.Button; import android.widget.Toast;
create a button and locate our button in the interface and apply it tot he newly created button.
final Button btn = (Button) findViewById(R.id.button1);
then add an eventlistener to it
btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Toast.makeText(getApplicationContext(), "Button clicked!", 100).show(); } });
It should be ready to go, here is what the end result s hould look like. I have also attached the project files for it tot his post.
No comments:
Post a Comment