- ToggleButton (Кнопка-переключатель)
- Общая информация
- Стилизация
- Android Switch (ON / OFF) Button with Examples
- Create Switch in XML Layout File
- Create Switch Control in Activity File
- Handle Switch Click Events
- Android Switch Control Attributes
- Android Switch Control Example
- activity_main.xml
- MainActivity.java
- Output of Android Switch Example
- Android Toggle Switch Button
- What is a Switch?
- Step 1: Create a new Project
- Step 2: Adding Switch to Android Activity
- Attributes of Switch with Example:
- 1. id Attribute:
- 2. checked Attribute:
- 3. text Attribute:
- 4. gravity Attribute:
- 5. textOn and textOff Attributes:
- 6. textColor Attribute:
- 7. textSize Attribute:
- 8. textStyle Attribute:
- 9. background Attribute:
- 10. padding Attribute:
- Different Listeners in Switch:
- 1. Using setOnClickListener(OnClickListener l) Listener:
- 2. Using setOnCheckedChangeListener(OnCheckedChangeListener l) Listener:
ToggleButton (Кнопка-переключатель)
Общая информация
Компонент ToggleButton по своей функциональности похож на флажок (checkbox) или переключатель (radiobutton) — это кнопка, которая может находиться в одном из двух состояний: активна (On) или неактивна (Off). По умолчанию на кнопке написано «Оn», если она активна, и «Off» — если нет. По внешнему виду это обычная кнопка с декоративной полоской в нижней части, которая подсвечивается в включенном состоянии (имитация LED-индикатора).
Находится в разделе Widgets:
Если надписи On/Off для вашей программы не подходят, их можно изменить при помощи свойств Text on (атрибут android:textOn) и Text off (атрибут android:textOff). Поскольку надписи Оn и Off на кнопке-переключателе являются отдельными атрибутами, атрибут android: text не используется, он доступен, так как наследуется от ТextView, но в данном случае без него можно обойтись. В программном коде им соответствуют методы setTextOff() и setTextOn().
По умолчанию, ToggleButton находится в выключенном состоянии, чтобы его «включить», установите свойство checked в значение true. Свойству соответствует метод setChecked(boolean checked).
Основное событие ToggleButton — изменение состояния кнопки onCheckedChanged().
Напишем демонстрационную программу с использованием ToggleButton. Добавим на форму метку, изображение и кнопку-переключатель:
Для создания обработчика события изменения состояния кнопки необходима реализация интерфейса CompoundButton.OnCheckedChangeListener. Интерфейс имеет единственный метод onCheckedChanged(), который необходимо переопределить в нашем классе. При обработке события для определения состояния используется параметр isChecked.
Стилизация
Создайте два изображения для каждого состояния кнопки-переключателя в формате 9-patch, например, btn_toggle_off.9.png и btn_toggle_on.9.png. Разместите картинки в папке res/drawable-hdpi/ (или в других).
Далее создаются два XML-файла в папке res/drawable:
btn_toggle_bg.xml (отвечает за фон):
btn_toggle.xml (выводит нужное изображение в разных состояниях)
Также можно определить стиль и тему для кнопки. В файле res/values/themes.xml пропишите:
Сообщите системе, что нужно использовать новый стиль для кнопки:
Источник
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.
Источник
Android Toggle Switch Button
In various Android apps, we have seen different types of switches such as YouTube (switch to autoplay the next video), Truecaller(switch to enable dark theme, block calls, call recording switch, etc.), in Facebook settings, Gmail, WhatsApp(to enable fingerprint lock for security) and many other apps.
What is a Switch?
In Android Studio Switch is a two-state toggle switch widget that can be used to select between two options. It is mainly used to display the on and off state of an option, which looks like a simple slider control to the user. The user may drag the «thumb» back and forth to choose the selected option, or we can simply tap to toggle the state of the switch.
It is commonly used in selecting on/off Hotspot, Flashlight, WiFi, etc. It is the subclass of android.widget.CompoundButton class.
The Switch is similar to a ToggleButton in accordance to the function but both of them have some differences such as Switch has a spider to control the state of the switch and the UI of both Switch and ToogleButton is different.
Now we have enough knowledge about switch let’s add a switch in our android app.
Step 1: Create a new Project
Open Your Android Studio Click on «Start a new Android Studio project«(Learn how to setup Android Studio and create your first Android project)
Choose «Empty Activity» from the project template window and click on Next.
Enter the App Name, Package name, save location, language(Java/Kotlin, we will use Java for this tutorial), and the minimum SDK(we are using API 19: Android 4.4 (KitKat))
Next click on Finish button after filling in the above details.
Now, wait for the project to finish building.
Step 2: Adding Switch to Android Activity
Now go to app -> res -> layout -> activity_main.xml and add Switch, now our activity_main.xml file will look like as shown below:
In the above code, we have added the default toggle switch in our Android Activity.
Attributes of Switch with Example:
Let’s know more about the attributes of Switch and how we can use them to customise the switch in android app.
1. id Attribute:
It is used to set a unique id for the switch by which we can identify a particular switch, it means different switches have different ids.
2. checked Attribute:
This attribute is used to set the current state of the Switch. The value can either be true or false and the default value of checked attribute is false. When we set checked=»true» the switch becomes checked by default and when we set it false the switch become unchecked.
We can also change the checked state of the switch in the Java code using the setChecked(Boolean b) function, where b can either true or false as shown below:
3. text Attribute:
It is used to set the text for the Switch. We can set the text directly as shown below:
Or we can also change the text dynamically in the Java code using the setText(CharcaterSwequence cs) function as shown below:
4. gravity Attribute:
It is used to set the gravity of the text in a Switch. The default value is left. There are many values of gravity such as right, left, center, center_horizontal, top, bottom, center_vertical, clip_horizontal, clip_vertical, end, fill, fill_horizontal, fill_vertical, and start. To view the effect of gravity we have to set android:layout_width = «match_parent»
We can also change the text gravity at runtime in the Java code by using the setGravity(int gravity) function as shown below:
5. textOn and textOff Attributes:
The textOn attribute is used to set the text which we want to shown when Switch is in the checked state (means in on state) and textOff attribute is used to set the text which we want to shown Switch is in the unchecked state (means in off state) as shown below. To show the textOff and textOn text we have set showText = «true»
We can also change the textOn and textOff values in the Java code by using the setTextOn(CharSeqence texton) and setTextOff(CharSeqence textoff) functions as shown below:
Output for textOff:
Output for textOn:
6. textColor Attribute:
It is used to set the text color of the switch. The color value can be any one of the form «#argb», «#rgb», «#rrggbb», or «#aarrggbb».
We can also do the same thing in the Java code using void setTextColor(int color) or void setTextColor(ColorStateList colors) functions as shown below:
7. textSize Attribute:
This attribute is used to set the size of the Switch text. We can set the size in dp, in, mm, pt, px, sp in XML. In the example below we are setting the text size to 32 dp:
We can change the text size from Java code by using the void setTextSize(float size) and void setTextSize(int unit, float size) functions:
8. textStyle Attribute:
It is used to set the text style of the Switch text. The 3 text styles available in android are bold, normal and italic. The default text style is normal and if we want to use more than one text style then we can use the | (pipe) operator between different styles, for example, bold | italic.
We can change the text style from the Java code too by using the void setTypeface( Typeface tf) and void setTypeface( Typeface typeface, int style ) functions as shown below:
9. background Attribute:
It is used to set the background of the switch. It can either be a color or drawable (image) or any custom xml file. For this tutorial we will add a simple red color background:
We can also set the background from the Java code using the void setBackgroundColor( int color) function:
10. padding Attribute:
It is used to set the padding to the Switch. We can either set the top, bottom, left, right padding at once using the padding attribute or we can add different padding for top, bottom, left, right using the paddingLeft , paddingRight , paddingTop , and paddingBottom attributes.
We can also add padding from the Java code too using the void setPadding( int left, int top, int right, int bottom ) function as shown below:
Different Listeners in Switch:
Now let’s cover the event or click listener functions which can be used to capture the user click on the toggle switch and perform some action.
1. Using setOnClickListener(OnClickListener l) Listener:
We can use this listener when we want to check if the switch is clicked and make a decision according to the click. Inside the public void onClick(View view) function, we will check if the switch is checked or not using the boolean isChecked() function and show toast to the user according to the state of the switch as shown below:
Here are the output screens:
2. Using setOnCheckedChangeListener(OnCheckedChangeListener l) Listener:
This listener is invoked when the state of the switch is changed means when we toggle the switch from off state to on state or vice versa. The main difference from onClickListener is that this is only invoked when the state changes, but onClickListener is invoked every time when we click on the Switch.
Inside the onCheckedChangeListener we have a onCheckedChanged(CompoundButton compoundButton, boolean b) and we can use a boolean value to check the state of the switch and perform the functions according the value of the boolean:
Here are the output screens:
There are many other listeners which we can use according to our needs. These 2 listeners are the most basic and any project can be made with these listeners without any problem.
Источник