DEV Community

Arzath Areeff
Arzath Areeff

Posted on

2

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

Sentry image

Make it make sense

Make sense of fixing your code with straight-forward application monitoring.

Start debugging →

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay