Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android Button OnClick Tutorial
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1"
android:onClick="showMessage"/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button2"
android:layout_below="@+id/button1"
android:layout_marginTop="32dp"/>
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button3"
android:layout_below="@+id/button2"
android:layout_marginTop="32dp"/>
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button4"
android:layout_below="@+id/button3"
android:layout_marginTop="32dp"/>
</RelativeLayout>
package com.devahoy.android.sample.button;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(this);
Button button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"Button3 Clicked!", Toast.LENGTH_SHORT).show();
}
});
Button button4 = (Button) findViewById(R.id.button4);
button4.setOnClickListener(Button4OnClick);
}
public void showMessage(View view) {
Toast.makeText(this, "Button1 Clicked!", Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View v) {
Toast.makeText(this, "Button2 Clicked!", Toast.LENGTH_SHORT).show();
}
View.OnClickListener Button4OnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"Button4 Clicked!", Toast.LENGTH_SHORT).show();
}
};
}
@AladinBayken

This comment has been minimized.

Copy link

@AladinBayken AladinBayken commented Jun 27, 2021

Hey, i want to create a Java class (none activity) so how can i make it in the class (method)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment