Choose Empty Activity.

Enter a project name.

Choose activity_main.xml.

Add a button.

Delete TextView (Hello World) by pressing Delete key

Add android:onClick attribute inside <Button> tag

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:onClick="onButtonClicked"
        tools:layout_editor_absoluteX="158dp"
        tools:layout_editor_absoluteY="316dp"
        tools:ignore="MissingConstraints" />

</androidx.constraintlayout.widget.ConstraintLayout>

Let's make a message appear when a button is pressed.

You need to link the button you added in activity_main.xml to MainActivity.java.

package com.jw.messageexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void onButtonClicked(View view){
        Toast.makeText(this,"Button clicked",Toast.LENGTH_LONG).show();

    }
}

That way, the click event from the button can be handled in the Java source.

Toast serves as a small, brief display of messages.

Press Alt + Enter to resolve import errors.

Run app

When you press the button, you can see that the message appears and disappears at the bottom of the screen.

 

 

 

 

 

+ Recent posts