This is going to be a real noob question, so please have mercy. I am trying to create a message box on a button click event in Android. I have read some examples on StackOverflow, but I can't seems to grasp the concept. In my main.xml file, I have defined the button xml as follows:
<Button
android:id="@+id/btnOK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display Message"
android:onClick="onBtnClicked" />
I read on one of the posts that I need to register the onClick event in the XML layout. So that is what I thought I did in the XML code above. Then, in my java code file, I have written the following code:
package com.example.helloandroid;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class HelloAndroid extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onBtnClicked(View v)
{
if(v.getId() == R.id.btnOK)
{
MessageBox("Hello World");
}
}
public void MessageBox(String message)
{
Toast.makeText(this, message, Toast.LENGTH_SHORT);
}
}
To me, this makes sense. But the message box does not display when I click on the button. From the code imports above, you can see that I have already tried a few solutions without success. Am I perhaps missing a listener? I thought that the definition in the XML code would create this for me?
Thanks in advance :-)
In Android, the OnClickListener() interface has an onClick(View v) method that is called when the view (component) is clicked. The code for a component's functionality is written inside this method, and the listener is set using the setOnClickListener() method.
You are setting the event handler on TextView not on Button . Set it on your Button . Save this answer.
An ImageButton is an AbsoluteLayout which enables you to specify the exact location of its children. This shows a button with an image (instead of text) that can be pressed or clicked by the user.
Change
Toast.makeText(this, message, Toast.LENGTH_SHORT);
To
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
The show() makes sure you actually display the Toast, else you are only creating the Toast.
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
- you need to call the show()
method as now you are just creating the toast without showing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With