On off buttons in android

Buttons

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

Depending on whether you want a button with text, an icon, or both, you can create the button in your layout in three ways:

  • With text, using the Button class:
  • With an icon, using the ImageButton class:
  • With text and an icon, using the Button class with the android:drawableLeft attribute:

Key classes are the following:

Responding to Click Events

When the user clicks a button, the Button object receives an on-click event.

To define the click event handler for a button, add the android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

For example, here’s a layout with a button using android:onClick :

Within the Activity that hosts this layout, the following method handles the click event:

Kotlin

The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:

  • Be public
  • Return void
  • Define a View as its only parameter (this will be the View that was clicked)

Using an OnClickListener

You can also declare the click event handler programmatically rather than in an XML layout. This might be necessary if you instantiate the Button at runtime or you need to declare the click behavior in a Fragment subclass.

To declare the event handler programmatically, create an View.OnClickListener object and assign it to the button by calling setOnClickListener(View.OnClickListener) . For example:

Kotlin

Styling Your Button

The appearance of your button (background image and font) may vary from one device to another, because devices by different manufacturers often have different default styles for input controls.

You can control exactly how your controls are styled using a theme that you apply to your entire application. For instance, to ensure that all devices running Android 4.0 and higher use the Holo theme in your app, declare android:theme=»@android:style/Theme.Holo» in your manifest’s element. Also read the blog post, Holo Everywhere for information about using the Holo theme while supporting older devices.

To customize individual buttons with a different background, specify the android:background attribute with a drawable or color resource. Alternatively, you can apply a style for the button, which works in a manner similar to HTML styles to define multiple style properties such as the background, font, size, and others. For more information about applying styles, see Styles and Themes.

Borderless button

One design that can be useful is a «borderless» button. Borderless buttons resemble basic buttons except that they have no borders or background but still change appearance during different states, such as when clicked.

To create a borderless button, apply the borderlessButtonStyle style to the button. For example:

Custom background

If you want to truly redefine the appearance of your button, you can specify a custom background. Instead of supplying a simple bitmap or color, however, your background should be a state list resource that changes appearance depending on the button’s current state.

You can define the state list in an XML file that defines three different images or colors to use for the different button states.

To create a state list drawable for your button background:

    Create three bitmaps for the button background that represent the default, pressed, and focused button states.

To ensure that your images fit buttons of various sizes, create the bitmaps as Nine-patch bitmaps.

Источник

Android Button with Examples

In android, Button is a user interface control that is used to perform an action whenever the user clicks or tap on it.

Generally, Buttons in android will contain a text or an icon or both and perform an action when the user touches it.

Читайте также:  Запустить андроид введите пин код что это такое

Following is the pictorial representation of using Buttons in android applications.

In android, we have a different type of buttons available to use based on our requirements, those are ImageButton, ToggleButton, RadioButton.

In android, we can create a Button control in two ways either in the XML layout file or create it in the Activity file programmatically.

Create Button in XML Layout File

Following is the sample way to define Button control in the XML layout file in the android application.

LinearLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :orientation= «vertical» android :layout_width= «match_parent»
android :layout_height= «match_parent» >
Button
android :id= «@+id/addBtn»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :text= «Add»/>
LinearLayout >

If you observe above code snippet, here we defined Button control in xml layout file.

Create Button Control in Activity File

In android, we can create Button control programmatically in an activity file based on our requirements.

Following is the example of creating Button control dynamically in the activity file.

LinearLayout layout = (LinearLayout)findViewById(R.id. l_layout );
Button btn = new Button( this );
btn.setText( «Test» );
layout.addView(btn);

Android Handle Button Click Events

Generally, whenever the user clicks on a Button, the Button object will receives an on-click event.

In android, we can define a button click event in two ways either in the XML layout file or create it in the Activity file programmatically.

Define Button Click Event in XML Layout File

We can define click event handler for button by adding android:onClick attribute to the element in our XML layout file.

The value of android:onClick attribute must be the name of the method which we need to call in response to a click event and the Activity file which hosting XML layout must implement the corresponding method.

Following is the example of defining a button click event using android:onClick attribute in an XML layout file.

xml version= «1.0» encoding= «utf-8» ?>
LinearLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :orientation= «vertical» android :layout_width= «match_parent»
android :layout_height= «match_parent» >
Button
android :id= «@+id/addBtn»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :text= «Add»
android :onClick= «addOperation»/>
LinearLayout >

In Activity that hosts our XML layout file, we need to implement click event method like as shown below

/** Called when the user touches the button */
public void addOperation(View view) <
// Do something in response to the button click
>

Define Button Click Event in Activity File

In android, we can define the button click event programmatically in the Activity file rather than XML layout file.

To define button click programmatically, create View.OnClickListener object and assign it to the button by calling setOnClickListener(View.OnClickListener) like as shown below.

Button btnAdd = (Button)findViewById(R.id. addBtn );
btnAdd.setOnClickListener( new View.OnClickListener() <
public void onClick(View v) <

// Do something in response to button click
>
>);
>

This is how we can handle button click events in android applications based on our requirements.

Android Button Control Attributes

Following are the some of commonly used attributes related to Button control in android applications.

Attribute Description
android:id It is used to uniquely identify the control
android:gravity It is used to specify how to align the text like left, right, center, top, etc.
android:text It is used to set the text.
android:textColor It is used to change the color of text.
android:textSize It is used to specify the size of the text.
android:textStyle It is used to change the style (bold, italic, bolditalic) of text.
android:background It is used to set the background color for button control.
android:padding It is used to set the padding from left, right, top and bottom.
android:drawableBottom It’s drawable to be drawn to the below of text.
android:drawableRight It’s drawable to be drawn to the right of text.
android:drawableLeft It’s drawable to be drawn to the left of the text.

Android Button Control Example

Following is the example of defining a one Button and two EditText controls in LinearLayout to get the data of EditText controls when click on Button in android application.

Create a new android application using android studio and give names as ButtonExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

xml version= «1.0» encoding= «utf-8» ?>
LinearLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :orientation= «vertical» android :layout_width= «match_parent»
android :layout_height= «match_parent» >
TextView
android :id= «@+id/fstTxt»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :layout_marginTop= «150dp»
android :text= «First Number»/>
EditText
android :id= «@+id/firstNum»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :ems= «10»/>
TextView
android :id= «@+id/secTxt»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :text= «Second Number»
android :layout_marginLeft= «100dp»/>
EditText
android :id= «@+id/secondNum»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :ems= «10»/>
Button
android :id= «@+id/addBtn»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :text= «Add»/>
LinearLayout >

If you observe above code we created one Button, two TextView controls and two EditText controls in XML Layout file.

Once we are done with the creation of layout with required control, we need to load the XML layout resource from our activity onCreate() callback method, for that open main activity file MainActivity.java from \java\com.tutlane.buttonexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.buttonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity <
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
final EditText firstNum = (EditText)findViewById(R.id. firstNum );
final EditText secNum = (EditText)findViewById(R.id. secondNum );
Button btnAdd = (Button)findViewById(R.id. addBtn );
btnAdd.setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
if ( firstNum .getText().toString().isEmpty() || secNum .getText().toString().isEmpty())
<
Toast.makeText(getApplicationContext(), «Please fill all the fields» , Toast. LENGTH_SHORT ).show();
>
else <
int num1 = Integer.parseInt( firstNum .getText().toString());
int num2 = Integer.parseInt( secNum .getText().toString());
Toast.makeText(getApplicationContext(), «SUM = » + (num1 + num2), Toast. LENGTH_SHORT ).show();
>
>
>);
>
>

If you observe above code we are calling our layout using setContentView method in the form of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file name activity_main and we are getting the values from two EditText controls on Button click and performing an addition operation.

Generally, during the launch of our activity, onCreate() callback method will be called by the android framework to get the required layout for an activity.

Output of Android Button Example

When we run above example using android virtual device (AVD) we will get a result like as shown below.

This is how we can use Button control in android applications to perform required operations on button tap or click based on our requirements.

Источник

Android Switch (ON / OFF) Button with Examples

In android, Switch is a two-state user interface element that is used to display ON (Checked) or OFF (Unchecked) states as a button with thumb slider. By using thumb, the user may drag back and forth to choose an option either ON or OFF.

The Switch element is useful for the users to change the settings between two states either ON or OFF. We can add a Switch to our application layout by using Switch object.

Following is the pictorial representation of using Switch in android applications.

By default, the android Switch will be in the OFF (Unchecked) state. We can change the default state of Switch by using android:checked attribute.

In case, if we want to change the state of Switch to ON (Checked), then we need to set android:checked = “true” in our XML layout file.

In android, we can create Switch control in two ways either in the XML layout file or create it in the Activity file programmatically.

Create Switch in XML Layout File

Following is the sample way to define Switch control in XML layout file in the android application.

If you observe above code snippet, here we defined Switch control and setting Switch state ON using android:checked attribute and textOff / textOn attributes are used to set the text to represent Switch state in xml layout file.

Create Switch Control in Activity File

In android, we can create Switch control programmatically in activity file based on our requirements.

Following is the example of creating Switch control dynamically in an activity file.

RelativeLayout layout = (RelativeLayout)findViewById(R.id. r_layout );
Switch sb = new Switch( this );
sb.setTextOff( «OFF» );
sb.setTextOn( «ON» );
sb.setChecked( true );
layout.addView(sb);

This is how we can define Switch in XML layout file or programmatically in activity file based on our requirements.

Handle Switch Click Events

Generally, whenever the user clicks on Switch, we can detect whether the Switch is in ON or OFF state and we can handle the Switch click event in activity file using setOnCheckedChangeListener like as shown below.

Switch sw = (Switch) findViewById(R.id.switch1);
sw.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() <
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) <
if (isChecked) <
// The toggle is enabled
> else <
// The toggle is disabled
>
>
>);

This is how we can handle Switch click events in android applications based on our requirements.

Android Switch Control Attributes

Following are the some of commonly used attributes related to Switch control in android applications.

Attribute Description
android:id It is used to uniquely identify the control
android:checked It is used to specify the current state of switch control
android:gravity It is used to specify how to align the text like left, right, center, top, etc.
android:text It is used to set the text.
android:textOn It is used to set the text when the toggle button is in the ON / Checked state.
android:textOff It is used to set the text when toggle button is in OFF / Unchecked state.
android:textColor It is used to change the color of the text.
android:textSize It is used to specify the size of the text.
android:textStyle It is used to change the style (bold, italic, bolditalic) of text.
android:background It is used to set the background color for toggle button control.
android:padding It is used to set the padding from left, right, top and bottom.
android:drawableBottom It’s a drawable to be drawn to the below of text.
android:drawableRight It’s a drawable to be drawn to the right of the text.
android:drawableLeft It’s drawable to be drawn to the left of the text.

Android Switch Control Example

Following is the example of defining a two Switch controls and one Button control in RelativeLayout to get the state of Switch controls when we click on Button control in the android application.

Create a new android application using android studio and give names as SwitchExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

xml version= «1.0» encoding= «utf-8» ?>
RelativeLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :layout_width= «match_parent» android :layout_height= «match_parent» >
Switch
android :id= «@+id/switch1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :switchMinWidth= «56dp»
android :layout_marginLeft= «100dp»
android :layout_marginTop= «120dp»
android :text= «Switch1:»
android :checked= «true»
android :textOff= «OFF»
android :textOn= «ON»/>
Switch
android :id= «@+id/switch2»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :switchMinWidth= «56dp»
android :layout_below= «@+id/switch1»
android :layout_alignLeft= «@+id/switch1»
android :text= «Switch2:»
android :textOff= «OFF»
android :textOn = «ON»/>
Button
android :id= «@+id/getBtn»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «150dp»
android :layout_marginTop= «200dp»
android :text= «Get»/>
RelativeLayout >

If you observe above code we defined a two Switch controls and one Button control in RelativeLayout to get the state of Switch controls when we click on Button control in XML layout file.

Once we are done with the creation of layout with required controls, we need to load the XML layout resource from our activity onCreate() callback method, for that open main activity file MainActivity.java from \java\com.tutlane.switchexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.switchexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity <
private Switch sw1 , sw2 ;
private Button btnGet ;
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
sw1 = (Switch)findViewById(R.id. switch1 );
sw2 = (Switch)findViewById(R.id. switch2 );
btnGet = (Button)findViewById(R.id. getBtn );
btnGet .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
String str1, str2;
if ( sw1 .isChecked())
str1 = sw1 .getTextOn().toString();
else
str1 = sw1 .getTextOff().toString();
if ( sw2 .isChecked())
str2 = sw2 .getTextOn().toString();
else
str2 = sw2 .getTextOff().toString();
Toast.makeText(getApplicationContext(), «Switch1 — » + str1 + » \n » + «Switch2 — » + str2,Toast. LENGTH_SHORT ).show();
>
>);
>
>

If you observe above code we are calling our layout using setContentView method in the form of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file name activity_main and we are trying to get the state of two Switch controls on Button click.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework to get the required layout for an activity.

Output of Android Switch Example

When we run the above example using an android virtual device (AVD) we will get a result like as shown below.

This is how we can use Switch control in android applications to switch the settings between two states either ON or OFF based on our requirements.

Источник

Читайте также:  Com android provider applications
Оцените статью