Click Event Button on Android

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 { /** 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); } } 

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: -)

+6
source share
4 answers

Change

 Toast.makeText(this, message, Toast.LENGTH_SHORT); 

For

 Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); 

The show () function ensures that you actually show Toast, otherwise you only create Toast.

+6
source

Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); - you need to call the show() method, since now you just create a toast without showing it.

+1
source
 Toast.makeText(this, message, Toast.LENGTH_SHORT); 

it is right

 Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); 
+1
source

The task should implement View.OnClickListener and implement the onClick (View v) method

in the onCreate method, you initialize the button (after the setContentView command):

 Button b = (Button) findViewById(R.id.btnOK); b.setOnClickListener(this); 

in the onClick method:

 public void onClick(View v) { switch(v.getId()){ case R.id.btnOK: /* the instruccions of the button */ break; } } 
0
source

Source: https://habr.com/ru/post/905472/


All Articles