BUTTON CLASS
A button is a widget in android which is sensitive to taps, touches or clicks from the user. Buttons communicate the action that will occur when the user touches, long presses or clicks the Button. The Button Class (android.widget. Button) is a subclass of TextView class from the broader View Class.

Different types of button widgets are available on the  Android Platform i.e. Button, ImageButton, RadioButton, CheckBox and ToggleButton .

Buttons

RadioButtons and CheckBoxes are used as selection widgets e.g. when we have to select from multiple options. Toggle button toggles between 2 states allowing a single state to be selected or deselected.

ImageButton displays a button with an image (instead of text) that can be pressed or clicked by the user

A button consists of text or an icon (or both text and an icon) that communicates what action occurs when the user touches it.

Please see the below snapshot  displaying text and icon buttons

_20170919_203404

BUTTON XML ATTRIBUTES
Android Buttons can be created either through the XML files or dynamically. Dynamic buttons require you to write code in the source code. This makes your code longer and less neat. Creating using XML affords you the luxury of dragging button element from the palette to the design editor which is quicker.

Let’s review some of the basic and important button attributes.

layout_width – this attribute defines the width of the button element relative to the parent. This is measured using density pixels abbreviated as dp. The value of layout_width can be set to wrap_content value which specifies that the button should be just big enough to enclose its contents plus the padding. The value match_parent is also used to specify that the button should be big as its parent but minus the padding. Kindly note that android:width attribute specifies the exact width of the Button in pixels as it will exactly appear in size on a device.

layout_length – this attribute is used to determine length of the of the button element relative to its parent. This is also measured using density pixels. The value of layout_length can be set to wrap_content or match_parent. android: length attribute specifies the exact length of the button in pixels.

id – is an attribute used to uniquely identify a Button so that we can reference it in our Java code.This attribute is used by findViewById method which looks through the view hierarchy and returns a reference to a view with the requested id. For the id value, you should usually use this syntax form:  “@+id/name” – the plus sign tells android to add or create a new id in in the resources.

text –  attribute is used to set the text in a Button. We can set the text in xml as well as in the java class.You should choose proper labels for your buttons, the rule of the thumb is to label buttons with what they do. Add a clear message of what happens after the button click.

textColor – textColor attribute is used to set the text color of a Button. Color value is in the form of Hex Colors i.e. “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.

background –  is used to set the background of a Button. We can set a color (both solid and gradient) or a drawable as the background of a Button.

textSize – textSize attribute is used to set the size of the button text.

textStyle –  textStyle attribute is used to set the text style of a Button. The possible text
styles are bold, italic and normal. If we need to use two or more styles for a button then “|” operator is used.

gravity – optional attribute which is used to control the alignment of the button text like left, right, center, top, bottom, center_vertical, center_horizontal etc.

drawableBottom, drawableTop, drawableRight And drawableLeft –  is the drawable to be drawn to left, right top or below of the text.

onClick  – this attribute supplies the name of the method of view’s context to invoke when the view is clicked.

visibility – this attribute controls the initial visibility of the view.

How to Draw a Default Flat Button
To draw a simple button open activity_main.xml and click the text tab. Replace the default layout root element with LinearLayout and then follow the steps outlined on the below slideshow to draw a default Button.

This slideshow requires JavaScript.

Below is the XML code ……………

 

BUTTON CUSTOMIZATION
Every button is styled using the system’s default button background, which is often different from one Android version to another. By default, the shape of the button is a rectangle, and the default color is gray.

If you are not satisfied with the default button style, you can customize it as we are about to do, but it is optional!

dragging the button

You can easily drag a button from the palette to the design editor as shown below.

Button Pic

To do this we need to first open the activity_main.xml and click on the text tab to open the xml editor. Highlight the default root tag and replace it with LinearLayout. Add orientation attribute to the parent linear layout and set its value to vertical

Switch back to the design tab and select widget on the palette. One at a time drag 2 button elements from the palette to the design editor. Switch back to the text tab and add the following lines ……………..

 

  • shadow attribute – adds a blurred shadow of text underneath the button text, the color is specified by shadowColor attribute. shadowDx and shadowDy attributes define the extent of the shadow reflection along the xy axis. shadowRadius sets the blur radius of the text shadow.
  • margin – Margins are the extra spaces surrounding the outside of a view, sort of an invisible barrier around the view. Margins ensure views are not touching each other and gives your user interface enough breathing space. layout_marginTop sets a margin above the view.  layout_marginBottom sets a margin below the view, layout_marginRight sets a margin to the right of the view. layout_marginLeft sets a margin to the left of the view. layout_marginEnd set the margin either to the left or to the right of the view depending on the whether the text is read from left-to-right or vice versa. layout_marginStart set the margin either to the left or to the right of the view depending on the whether the text is read from left-to-right .
  • padding – is the space between the view’s inner border and the actual view’s content. For a button, padding is a way to push the button text away from button’s inner borders.  paddingLeft keep distance from the left inner boundary.  paddingRight keep distance from the right inner boundary. paddingTop keep distance from the top inner boundary. paddingBottom – keep distance from the bottom inner boundary. padding keep distance from all the inner boundaries. If I may say it, padding makes a view fatter and and apper stuffed!
  • background –  This is a drawable or color which is responsible for use as the button’s background.
  • Shape – Another customization is to make buttons square or square with rounded corners. Some research suggests that rounded corners enhance information processing and draw our eyes to the center of the element.

To define the last two attributes we need to create a separate drawable XML file under the drawable folder which we will call custom_button.xml. This process is summarized on the below slideshow.

This slideshow requires JavaScript.

This  full is xml code for custom_button.xml is shown below …………….

 

Now run your app and compare the first button to the second default button. You will appreciate the first button is detailed with additional features making it more professional!

But nothing happens when we touch our buttons, something very important is missing so let see what is missing.

 

SETTING LISTENER TO A BUTTON
In order for the buttons to actually do something useful and respond to clicks, we’ll need to define onClickListeners for each button.

Important things to know are:

  • You need to add a listener to the Button
  • The listener interface you need is called onClickListener
  • You add the listener with the setOnClickListener(OnClickListener listener) method
  • You need to implement the onClick(View v) method -whatever action that needs to be performed on clicking the button must be coded within  the onClick method.
  • can replace OnClickListener with any other interface relevant to Button e.g. OnDragListener,OnLongClickListener and onFocusChangeListener

The are 3 ways to add a listener to the button.

An Anonymous Inner class
This method is very quick but does leave a bit of a mess. I would only recommend using this for small blocks of code because it clutters up the onCreate () especially for multiple buttons. The other issue is difficulty o test what happens when you invoke the click method during debugging mode.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MainActivity extends AppCompatActivity {
/*declare the buttons here so that they can be available to other methods*/
private Button btnCustomized, btnDefault;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*getting the buttons ids*/
btnCustomized = (Button) findViewById(R.id.customizedButton);
btnDefault = (Button)findViewById(R.id.defaultButton);

/*adding a new anonymous OnclickListener with setOnClickListener method*/
btnCustomized.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*implementing the onClick()method to display a Toast Message*/
Toast.makeText(MainActivity.this, "Customized Button Clicked!", Toast
.LENGTH_SHORT).show();
}
});

}
}

Private Variable
The second way of creating an OnClickListener is by adding a private variable to our class. OnClickListener is just an instance of a class, so it can be stored in a variable. This method is very suited for larger blocks of code and makes your code more organized.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class MainActivity extends AppCompatActivity {
/*declaring the buttons*/
private Button btnCustomized, btnDefault;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*getting the buttons ids*/
btnCustomized = (Button) findViewById(R.id.customizedButton);
btnCustomized.setOnClickListener(listener);
}
/*creating onClickListener instance and implementing the onClick method*/
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Customized Button Clicked", Toast.LENGTH_SHORT)
..show();
}
};
}

One of the benefits of using a private variable is that you can reuse it for other views. The onClick method passes the clicked view as a variable, you can use a switch statement to determine which view was clicked.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class MainActivity extends AppCompatActivity {
/*declaring the buttons*/
private Button btnCustomized, btnDefault;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*getting the buttons ids*/
btnCustomized = (Button) findViewById(R.id.customizedButton);
btnCustomized.setOnClickListener(listener);
btnDefault =(Button) findViewById(R.id.defaultButton);
btnDefault.setOnClickListener(listener);
}
/*creating onClickListener instance and implementing the onClick method*/
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
/*switch statetement to help identify the clicked button*/
switch (v.getId()){
case R.id.customizedButton:
Toast.makeText(MainActivity.this, "Customized Button Clicked", Toast.LENGTH_SHORT)
.show();
break;
case R.id.defaultButton:
Toast.makeText(MainActivity.this, "Default Button Clicked", Toast.LENGTH_SHORT)
.show();
break;
}

}
};
}

XML Reference
You can bind OnClickListeners to the view on defined in a  layout file. This might be the cleanest solution, but does come with a drawback that it can only be used for layouts that are inflated for an activity. It can not be used with android fragments.

To do this you need to first create a Button on your activity XML file and the onClick attribute to the button. Its value should be the name of the method declared on the source code.

………………………………………

In our activity class we add the onclick method which takes a view.

java

That is it about the Android Button, if you like it please let me know

Leave a Reply