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 mobile image

App store rankings love fast apps - mobile vitals can help you get there

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read full post →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay