Button View

Button,as we can understand by its name, is a component which can be tap or clicked by the user to perform an action and It has the same properties as a TextView.
Below we have specified how 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 tap a button then we can set a method that will handle that specific button request and will carry out the necessary action and this can be done inside the Activity class as following:

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 click on the button with id btn_submit then the above mentioned method is get called which run the code inside it.

Using android:onClick to add behaviour to Button

We can assign a method directly in the layout XML while defining the button using and 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 the user clicks on the Button mentioned in the above layout xml file,An android system will call study(View) this method and defined in MainActivity.java file. In order for this to work, the method should be public and accept a View type as its parameter.

public void study(View view) {

    //Perform action on click
    
}

Same way, the android:onClick attribute can be used with all the available View sub classes like, EditText, TextView, CheckBox and RadioButton etc.

Commonly used attributes for Button

Here are some commonly used attributes to style the Button View

  • android:gravity: This is used to set the position of any View on the app screen. The available values are right, left, center etc. we can also use to values together, using the | symbol.
  • android:textSize: To set text size inside button ui.
  • android:background: To set the background color of the button ui.
  • Picture can be added to the button ui, alongside the text by using android:drawableRight, android:drawableTop and android:drawableBottom, respectively.

Output:

Subscribe Now