In Android development, Button is a fundamental UI element that lets users perform actions when clicked. To respond to user interactions, we use click listeners such as setOnClickListener()
. This allows your app to react when the user taps a button — for example, displaying a message or opening a new screen.
Add Button in activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Enter your name:" android:textSize="18sp" android:layout_marginBottom="10dp" /> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Type your name here" android:inputType="textPersonName" android:layout_marginBottom="10dp"/> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Submit" /> </LinearLayout>
Add Java Code in MainActivity.java

package com.example.myfirstapp; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView textView; EditText editText; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); editText = findViewById(R.id.editText); button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String input = editText.getText().toString().trim(); if (!input.isEmpty()) { textView.setText("Hello, " + input + "!"); } else { textView.setText("Please enter your name."); } } }); } }
Output Example:
If user types “John” and taps Submit, TextView
will show:
“Hello, John!”
Summary:
Now you’ve learned how to:
- Create a layout with
TextView
,EditText
, andButton
- Read input from
EditText
- Show output in
TextView
when button is pressed
- Create a layout with