DEV Community

Arzath Areeff
Arzath Areeff

Posted on

Android App with Button Click Event and Toast Message

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();
            }
        });
    }

Enter fullscreen mode Exit fullscreen mode

Top comments (0)