Search code examples
javaandroidbuttontoast

Java-app closes, when i push Button to start a Toast. But why?


I made VERY simple java toast that appears when you press a button. But when I run it on my phone, it stops the app and quits without an error. What did I do wrong?

MainActivity:

package com.example.ras.tests;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


    }

    public void buttonWasClicked(View Button) {
        Toast.makeText(this , "Button wurde geklickt!" , Toast.LENGTH_SHORT).show();
    }
}

Button:

<Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:layout_marginTop="16dp"
    app:layout_constraintTop_toTopOf="@+id/activity_main"
    android:layout_marginStart="16dp"
    app:layout_constraintLeft_toLeftOf="@+id/activity_main"
    android:layout_marginLeft="16dp"
    android:onClick="buttonWasClicked (MainActivity)"
    android:visibility="visible" />
</android.support.constraint.ConstraintLayout>

Solution

  • Simple: android:onClick="buttonWasClicked" in your xml should do the trick. Or in your OnCreate method you can assign listener to your button like this:

    final Button button = (Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    buttonWasClicked(button);
                }
            });
    

    In this case you delete android:OnClick from your xml. And you can do it event better: remove parameter View button from method buttonWasClicked this allows you not to declare your variable final.