Android studio switch переключатель

Switch

Switch — ещё один вид переключателей, который появился в Android 4.0 (API 14). Находится в разделах Commons и Buttons. Фактически, это замена немного устаревшего ToggleButton. В новых проектах лучше использовать Switch.

Компонент используется в том случае, когда нужно переключиться на противоположное состояние — да/нет, вкл./выкл., открыть/закрыть. В реальной жизни это выглядит следующим образом.

При добавлении компонента в макет студия рекомендует использовать использовать SwitchCompat или SwitchMaterial. Общий принцип работы у них одинаковый, отличия касаются дизайна.

Компонент представляет собой полоску с двумя состояниями и сопровождающим текстом. Переключиться можно сдвиганием ползунка или касанием экрана в области компонента (не только на самом ползунке, но и на сопровождающем тексте).

По умолчанию компонент находится в выключенном состоянии. Чтобы установить его в включённом состоянии на этапе разработки, используйте атрибут android:checked=»true».

Сопровождающий текст задаётся в атрибуте android:text. А текст на самом переключателе задаётся при помощи атрибутов android:textOn (методы getTextOn() и setTextOn()) и android:textOff (методы getTextOff() и setTextOff()). Обратите внимание, что сопровождающий текст может быть очень большим и положение самого переключателя относительно этого текста можно регулировать при помощи атрибута android:gravity (смотри пример ниже). Если сопровождающий текст вам не нужен, то не используйте атрибут android:text.

Момент переключения можно отслеживать при помощи слушателя CompoundButton.OnCheckedChangeListener.

SwitchCompat

Студия рекомендует использовать SwitchCompat. Явных отличий у него нет.

Для показа текста на кнопке переключателя установите в true значение атрибута app:showText.

Не забывайте, что данный компонент можно использовать только в активностях типа AppCompatActivity.

Вы можете задать свой стиль для SwitchCompat, добавив строки в styles.xml

Цвет дорожки, вдоль которой двигается ползунок, можно поменять также через стиль:

Источник

Android studio switch переключатель

September 19, 2017

This post shows how to use android switch button, apply material styles, create custom styles, create custom switch button and how to handle switch button click events.

Android Switch XML Element

Android Switch Properties

Some of the important switch properties are textAppearance, textColor, track, thumb, switchTextAppearance, textOn, testOff, background, and showText.

Property thumb is used to set a drawable that switches back and forth, property track is used for setting a drawable as track for switch thumb, textOn and textOff are used to set text to be displayed when switch is in on or off state, textswitchTextAppearance is used to set style for switch text, and showText is used to indicate whether to show switch text or not.

Android Switch Material Style

Android system provides many material themes. When application level theme is set to one of the material themes, android switch will be displayed applying default switch material theme of the application theme used in the application. Below screen shot shows switch button in both on and off states when application theme is set to Theme.AppCompat.

Android Switch Button Custom Style Application Level

Application level themes can be customized by setting properties to custom values. If you customize properties related to UI controls, the changes will be applied to all UI controls and throughout the application. To change switch text color and switch button color, you need to set textColorPrimaryDisableOnly and colorAccent properties to custom values.

Below theme is an example of custom application theme added to res/values/styles.xml file. You can apply it to an application by setting theme attribute of application element in mainifest xml file.

Below screen shot shows switch button after application theme is set to custom material theme defined above.

Android Switch Custom Style Individual

If you want to change switch style only in a particular section of your application, then define custom switch widget style by inheriting Widget.AppCompat.CompoundButton.Switch as shown below and apply it to switch elements using theme attribute.

Switch attribute colorControlActivated can be used to set track and thumb color when switch is active and colorForeground can be used to set track color when switch is in normal state.

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

You can use thumbTint and trackTint properties to change color of thumb and track. Applying colors to track and thumb using selector xml allows you to apply different colors for different states, see custom switch section.

Android Switch Event Listener

Switch on and off events or switch drag event can be handled in two ways. One way of handling switch click event is by defining a method in your activity or fragment with View as input parameter and setting it as value for onClick attribute of Switch in layout xml as shown below.

Second way of handling switch on/off event is by defining OnCheckedChangeListener and adding it to switch button by using setOnCheckedChangeListener method.

Custom Switch Button

Android switch with custom track

You can customize android switch track by defining a drawable xml resource as shown below. You need to save it in res/drawable folder, our example file name switch_track_custom.xml, and apply it to switch by using track attribute.

Below xml, used as switch_color in the above drawable, is color selector for track. Color is applied based on the state of switch. This file needs to be saved in res/color folder.

Below xml shows applying the custom track drawable to Switch.

Output of custom track of switch.

Android switch with custom thumb

Android switch thumb can be customized by using material icon and defining drawable xml resource.

To do that, first download one of the android material icons which you want to use in your application or use any other image you may have and save it in res/drawable folder.

Then define drawable xml resource as shown below in res/drawable folder, our example file name is switch_thumb_custom.xml. This xml uses the above downloaded icon, defines shape and sets colors. To apply this to a switch, set its thumb attribute to the drawable xml.

In the above xml switchTrackNormal and switchThumbBgActive are colors defined in res/values/colors.xml

Below color selector xml saved as switch_color.xml is used in the custom thumb drawable xml defined above.

Below switch element in layout xml uses above custom switch thumb and switch track.

With switch button track customization explained from above section and switch button thumb customization explained in this section, the custom switch button will appear as shown below in normal and active states.

About

Android app development tutorials and web app development tutorials with programming examples and code samples.

Источник

Какие технологии нужны, чтобы использовать switch в android

Хочу сделать активити для настройки уведомления. Что вообще нужно использовать при работе со свитчем? условно хочу, чтобы при активированном свитче уведомления приходили, а когда свитч в положении off, уведомления не приходили.

1 ответ 1

Вопрос поставлен довольно странно на мой субъективный взгляд. Обратимся к документации:

Переключатель — это виджет с двумя состояниями, который может выбирать между двумя вариантами. Пользователь может перетаскивать «большой палец» назад и вперед, чтобы выбрать выбранную опцию, или просто нажать, чтобы переключиться, как если бы это был флажок. Свойство text управляет текстом, отображаемым в метке для переключателя, тогда как текст off и on управляет текстом на большом пальце. Точно так же textAppearance и связанные методы setTypeface() управляют гарнитурой и стилем текста метки, тогда как методы switchTextAppearance и связанные с ним setSwitchTypeface() управляют таковыми для большого пальца.

вот еще например можно встретить такое определение:

Switch — ещё один вид переключателей, который появился в Android 4.0 (API 14). Находится в разделах Commons и Buttons. Фактически, это замена немного устаревшего ToggleButton. В новых проектах лучше использовать Switch.

Вот пример работы с виджетом. Для начала добавляем в xml:

На этом технологии заканчиваются. Знаний по технологиям почти не нужно, есть только главная технология которую мы все должны знать в совершенстве — вот она. Эта на первый взгляд простая технология открывает путь к многим секретам и плюшкам 🙂

Теперь по поводу сохранения состояния. Я бы советовал использовать sharedPreferences для этих целей. Таким образом вы сможете программно сохранить в памяти телефона значение отвечающее какой-то функции. При включении switch делаем так в слушателе нажатий на виджет:

переменная isChecked находится здесь:

Дальше при запуске приложения мы проверяем есть ли что-то в памяти и устанавливаем значение в виджете:

А уже что делать при том или ином состоянии виджета вам решать 🙂

Источник

android.widget.Switch — on/off event listener?

I would like to implement a switch button, android.widget.Switch (available from API v.14).

Читайте также:  Android studio edittext onfocuschangelistener

But I’m not sure how to add an event listener for the button. Should it be an «onClick» listener? And how would I know if it is toggled «on» or not?

10 Answers 10

Switch inherits CompoundButton ‘s attributes, so I would recommend the OnCheckedChangeListener

Use the following snippet to add a Switch to your layout via XML:

Then in your Activity’s onCreate method, get a reference to your Switch and set its OnCheckedChangeListener:

For those using Kotlin, you can set a listener for a switch (in this case having the ID mySwitch ) as follows:

isChecked is true if the switch is currently checked (ON), and false otherwise.

Define your XML layout:

Then create an Activity

======== For below API 14 use SwitchCompat =========

The layout for Switch widget is something like this.

In the Activity class, you can code by two ways. Depends on the use you can code.

You can use DataBinding and ViewModel for Switch Checked Change event

September 2020 — Programmatically Answer

You can do it with programmatically for Switch Widget and Material Design:

My solution, using a SwitchCompat and Kotlin. In my situation, i needed to react to a change only if the user triggered it through the UI. In fact, my switch reacts to a LiveData , and this made both setOnClickListener and setOnCheckedChangeListener unusable. setOnClickListener in fact reacts correctly to user interaction, but it’s not triggered if the user drags the thumb across the switch. setOnCheckedChangeListener on the other end is triggered also if the switch is toggled programmatically (for example by an observer). Now in my case the switch was present on two fragments, and so onRestoreInstanceState would trigger in some cases the switch with an old value overwriting the correct value.

So, i looked at the code of SwitchCompat, and was able to mimic it’s behaviour successfully in distinguishing click and drag and used that to build a custom touchlistener that works as it should. Here we go:

the actual touch listener that accepts a lambda with the code to execute:

For the sake of completeness, this is how the observer for the state switchstate (if you have it) looked like:

Источник

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
>
>
>);

Читайте также:  Play movies on android

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.

Источник

Оцените статью