Android App with Button Click Event and Toast Message

Arzath AreeffArzath Areeff
2 min read

This code is an example of an Android app that demonstrates the use of a button click event and a Toast message. The app contains a layout with a button and a text field.

🔺The onCreate() method initializes the button and text field.

🔺The setOnClickListener() method is used to set an event listener on the button that listens for click events.

🔺When the button is clicked, a Toast message is displayed with the text entered in the text field.

🔺The findViewById() method is used to get a reference to the button and text field views, using their resource IDs.

🔺The getText().toString() method is used to get the text entered in the text field and store it in a string variable.

🔺Finally, the makeText() method is used to create a Toast message that displays the entered text, and the show() method is called to display the message.

This code can be used as a starting point for building more complex Android apps that require event handling and user input.

package com.example.parttime;

import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    private Button buttonOB;
    private TextView editTextOB;



    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(this, "On Create", Toast.LENGTH_SHORT).show();
        buttonOB=findViewById(R.id.ClickMeBtn);
        editTextOB=findViewById(R.id.editText);

        buttonOB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String nameStr;
                nameStr=editTextOB.getText().toString();

                Toast.makeText(MainActivity.this, nameStr, Toast.LENGTH_SHORT).show();
            }
        });
    }
0
Subscribe to my newsletter

Read articles from Arzath Areeff directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Arzath Areeff
Arzath Areeff

I co-founded digizen.lk to promote online safety and critical thinking. Currently, I’m developing an AI app to fight misinformation. As Founder and CEO of ideaGeek.net, I help turn startup dreams into reality, and I share tech insights and travel stories on my YouTube channels, TechNomad and Rz Omar.