jcobo1
jcobo1

Reputation: 1180

OnClick method on Android Studio is not working

I'm trying to show a message using a toast when you click one button. I did one OnClick ethod, but I don't know why is not executing when I click on the button.

MainActivit.java:

public class MainActivity extends Activity implements View.OnClickListener {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.i("OnCreat", "OnCreate method has been executed");
 }



   // Metodo listener para los botones (en este caso el boton Aplica)
@Override
public void onClick(View v) {
    Log.i("startMethod", "method has startes");
    Toast.makeText(v.getContext(), "botosi", Toast.LENGTH_LONG).show();
    Log.i("showToast", "toast should been displayed");
}


}

Upvotes: 1

Views: 6381

Answers (1)

Giorgio Antonioli
Giorgio Antonioli

Reputation: 16224

You have to initialize your button in your onCreate() something like:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.i("OnCreate", "OnCreate method has been executed");

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

But before ask here any question, please read some documentation on https://developer.android.com, this is just a basic question.

Upvotes: 3

Related Questions