Button View in Android
Button
, as understood by its name, is a component which can be pressed or clicked by the user to perform an action. It has the same properties as a TextView
, with a few Button specific properties.
Below we have specified how to define a button view in your android application using the layout XML:
<Button
android:id="@+id/btn_submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:textColor="@android:color/holo_blue_dark"
/>
The main usage of the Button
view is that whenever we click a button, we can set a method that will handle that specific button request and will carry out the necessary action. This can be done inside the Activity
class as following:
Note: If you do not know about the Activity
class as of now, do not worry. We will explain it very soon.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// creating instance of button
Button b = (Button) findViewById(R.id.btn_submit);
// setting on click event listener
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
}
}
Therefore, whenever we press the button with id
btn_submit, the above method is called which executes the code inside it.
Using android:onClick
to add behaviour to Button
We can also assign a method directly in the layout XML while defining the button using, android:onClick
attribute, like specified below.
<Button
android:id="@+id/btn_submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:textColor="@android:color/holo_blue_dark"
android:onClick="study"
/>
When user will click on the Button defined in the above layout xml file, then Android system will call study(View)
method, defined in MainActivity.java
file. In order for this to work, the method must be public
and accept a View
type as its only parameter.
public void study(View view) {
//Perform action on click
}
Similarly, the android:onClick
attribute can be used with all the available View subclasses, like TextView, EditText, RadioButton, CheckBox etc.
Output Screen
Commonly used attributes for Button
Here are some commonly used attributes for styling the Button View
android:gravity
: This can be used to set the position of any View on the app screen. The available value are right, left, center, center_vertical etc. You can also use to values together, using the |
symbol.
android:textSize
: To set text size inside button.
android:background
: To set the background color of the button.
- Picture can be added to the button, alongside the text by using
android:drawableRight
, android:drawableLeft
, android:drawableTop
and android:drawableBottom
, respectively.: