Button Example
Button Example
In the button example of a button we display two buttons with different background
and whenever a user clicks on the button the text of the button will be displayed in a
toast. https://abhiandroid.com/ui/button
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/simpleButton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:background="#00f"
android:drawableRight="@drawable/ic_launcher"
android:hint="Button1"
android:padding="5dp"
android:textColorHint="#fff"
android:textSize="20sp"
android:textStyle="bold|italic" />
<Button
android:id="@+id/simpleButton2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#f00"
android:drawableLeft="@drawable/ic_launcher"
android:hint="Button2"
android:padding="5dp"
android:textColorHint="#fff"
android:textSize="20sp"
android:textStyle="bold|italic" />
</RelativeLayout>
Step 3: In the MainActivity.java add the following code. Using the button
setOnClickListener() method and the Toast display which button is clicked by the user.
package example.abhiandriod.buttonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleButton1 = (Button) findViewById(R.id.simpleButton1);//get id of butt
on 1
simpleButton2 = (Button) findViewById(R.id.simpleButton2);//get id of butt
on 2
simpleButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Simple Button 1", Toast.L
ENGTH_LONG).show();//display the text of button1
}
});
simpleButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Simple Button 2", Toast.L
ENGTH_LONG).show();//display the text of button2
}
});
}
}
Output:
Run the application and then click on any button and see the message on screen which
button is clicked.