This will be the real question about the noob, so please have mercy. I am trying to create a message box in a button click event in Android. I read a few examples on StackOverflow, but I can not understand the concept. In my main.xml file, I defined the xml button 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 this is what I thought in the XML code above. Then, in my java code file, I wrote 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 { @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); } }
It makes sense to me. But the message box does not appear when I click the button. From the above code, you can see that I have already tried several solutions without success. Maybe I'm missing a listener? I thought a definition in XML code would create this for me?
Thanks in advance: -)
source share