Android studio switch material

Содержание
  1. Switch
  2. SwitchCompat
  3. Android studio switch material
  4. Android Switch XML Element
  5. Android Switch Properties
  6. Android Switch Material Style
  7. Android Switch Button Custom Style Application Level
  8. Android Switch Custom Style Individual
  9. Android Switch Event Listener
  10. Custom Switch Button
  11. Android switch with custom track
  12. Android switch with custom thumb
  13. About
  14. Hands-on with Material Components for Android: Selection Controls
  15. Part 8 of a series covering practical usage of Material Components for Android
  16. Setting up a Material Components theme for Android
  17. Attribute by attribute
  18. Basic usage 🏁
  19. Setting and listening for checks 👂
  20. Grouping Selection Controls 👨‍👩‍👧‍👦
  21. Theming 🎨
  22. Color
  23. Typography
  24. Shape
  25. More resources 📚
  26. Tutorialwing
  27. Output
  28. Getting Started
  29. Creating New Project
  30. Setup ViewBinding
  31. Using Material Switch in Kotlin
  32. Different Attributes of Material Switch in XML
  33. Set Id of Material Switch
  34. Set Width of Material Switch
  35. Set Height of Material Switch
  36. Set Padding of Material Switch
  37. Set Margin of Material Switch
  38. Set Background of Material Switch
  39. Set Visibility of Material Switch
  40. Set Text of Material Switch
  41. Set Color of Text in Material Switch
  42. Set Gravity of Material Switch
  43. Set Text in Uppercase, Lowercase
  44. Set text in uppercase
  45. How do we set text in lowercase?
  46. Set Size of Text in Material Switch
  47. Set Style (Bold/italic) of Text in Material Switch
  48. Set Letter Spacing of Text in Material Switch
  49. Set Typeface of Text in Material Switch
  50. Set fontFamily of Text in Material Switch
  51. Different Attributes of Android Material Switch Widget

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 material

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.

Источник

Hands-on with Material Components for Android: Selection Controls

Part 8 of a series covering practical usage of Material Components for Android

This post will be covering the features and APIs of Radio Button, Checkbox and Switch components. To find out how to handle initial setup of Material Components for Android (including the Gradle dependency and creating an app theme), please see my original post:

Setting up a Material Components theme for Android

Attribute by attribute

Selection Controls are small components for scenarios in which users need to select options or toggle settings. They are typically found on settings screens and dialogs.

From a design perspective, there are three main types of selection controls which can be used in different scenarios:

  • Radio Buttons: A circular control with two possible states; selected or unselected. Has single-select behavior when in a group of other radio buttons (i.e. Only one control can be selected at a time).

  • Checkboxes: A square control with two possible states; checked or unchecked. Has multi-select behavior when in a group of other checkboxes (i.e. Multiple controls can be selected at a time).

  • Switches: A control consisting of a thumb and a track. Has two possible states; on or off.

Basic usage 🏁

A MaterialRadioButton , MaterialCheckBox or SwitchMaterial can be included in your layout like so:

Setting and listening for checks 👂

All of the selection controls extend from the base CompoundButton class. As such, they inherit a checkable behavior that can be toggled both programmatically and via touch interaction.

A selection control can be programmatically toggled:

Listening for checked/unchecked state changes is done like so:

Grouping Selection Controls 👨‍👩‍👧‍👦

Selection controls are commonly used in groups. Strictly speaking, any ViewGroup can be used to achieve this (eg. a RecyclerView ). That being said, the RadioGroup class exists to specifically handle single-select behavior for MaterialRadioButton s.

MaterialRadioButton s can be grouped with a RadioGroup like so:

A number of APIs exist for programmatically setting, getting and listening for changes to child MaterialRadioButton checked/unchecked state:

Theming 🎨

Selection controls can be themed in terms of the three Material Theming subsystems: color, typography and shape. When implementing global custom MaterialRadioButton , MaterialCheckBox and SwitchMaterial styles, reference them in your app theme with the radioButtonStyle , checkboxStyle and switchStyle attributes respectively.

Color

The color of selection controls defaults to colorOnSurface (unchecked) and colorControlActivated i.e. colorSecondary (checked) defined in your app theme. In order to override this on a per-control level, you will need to either:

  • Use a theme overlay with the above-mentioned color attributes present, applied to the widget with the android:theme attribute.
  • Set the useMaterialThemeColors attribute to false and apply a custom tint ColorStateList using CompoundButtonCompat#setButtonTintList .

Typography

The text labels of the selection controls will adopt the fontFamily attribute defined in your app theme. In order to override this in a style or on a per-control level, use the android:textAppearance attribute.

Shape

There are no aspects of any of the selection controls that can be adjusted with shape theming.

More resources 📚

  • The source code for the Playground app used in this article can be found on GitHub.
  • Selection Controls Design Documentation
  • Radio Button API Documentation
  • Checkbox API Documentation
  • Switch API Documentation

I hope this post has provided some insight into radio buttons, checkboxes and switches and how they can be used in your Android app(s). If you have any questions, thoughts or suggestions then I’d love to hear from you!

Источник

Tutorialwing

In this article, we will learn about android Material Switch using Kotlin. We will go through various example that demonstrates how to use different attributes of Material Switch. For example,

Читайте также:  Wifi модем для android

In this article, we will get answer to questions like –

  • What is Material Switch?
  • Why should we consider Material Switch while designing ui for any app?
  • What are possibilities using Material Switch while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Android Switch Output

Tutorialwing Android Switch Output

Getting Started

We can define android Material Switch widget as below –

Android Switch is a two-state toggle widget that can select between two options (ON or OFF). The user can drag and drop thumb to select between two options or it can simply tap to toggle the state.

Now, how do we use Material Switch in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as SwitchMaterial. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android Material Switch Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

Now, we can access view in Kotlin file without using findViewById() method.

Using Material Switch in Kotlin

Follow steps below to use Material Switch in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
  • Open res/layout/activity_main.xml file. Then, add below code in it –

In activity_main.xml file, we have defined Switch widget. Now, we will access this Switch using kotlin file in the application.
We can also access it in Kotlin File, MainActivity.kt, as below –

In MainActivity.kt file, we have accessed Switch widget defined in xml file. Then, we have set a checked change listener to show a toast message whenever checked state is changed.

Now, run the application. We will get output as below –

Tutorialwing Android Switch Output

Tutorialwing Android Switch Output

Different Attributes of Material Switch in XML

Now, we will see how to use different attributes of Android Material Switch using Kotlin to customise it –

Set Id of Material Switch

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of Material Switch using android:id attribute like below –

Here, we have set id of Material Switch as materialSwitch_ID using android:id=”” attribute. So, if we need to reference this Material Switch, we need to use this id – materialSwitch_ID.
Learn to Set ID of Material Switch Dynamically

Set Width of Material Switch

We use android:layout_width=”” attribute to set width of Material Switch.
We can do it as below –

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of Material Switch Dynamically

Set Height of Material Switch

We use android:layout_height=”” attribute to set height of Material Switch.
We can do it as below –

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of Material Switch Dynamically

Set Padding of Material Switch

We use android:padding=”” attribute to set padding of Material Switch.
We can do it as below –

Here, we have set padding of 10dp in Material Switch using android:padding=”” attribute.
Learn to Set Padding of Material Switch Dynamically

Set Margin of Material Switch

We use android:layout_margin=”” attribute to set margin of Material Switch.
We can do it as below –

Here, we have set margin of 10dp in Material Switch using android:layout_margin=”” attribute.
Learn to Set Margin of Material Switch Dynamically

Set Background of Material Switch

We use android:background=”” attribute to set background of Material Switch.
We can do it as below –

Here, we have set background of color #ff0000 in Material Switch using android:background=”” attribute.
Learn to Set Background of Material Switch Dynamically

Set Visibility of Material Switch

We use android:visibility=”” attribute to set visibility of Material Switch.
We can do it as below –

Here, we have set visibility of Material Switch using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of Material Switch Dynamically

Set Text of Material Switch

We use android:text=”” attribute to set text of Material Switch.
We can do it as below –

Here, we have set text (“Hello Tutorialwing”) in Material Switch using android:text=”” attribute.
Similarly, we can set any text using this attribute.
Learn to Set Text of Material Switch Dynamically

Set Color of Text in Material Switch

We use android:textColor=”” attribute to set color of text in Material Switch.
We can do it as below –

Here, we have set color (#ffffff i.e. white) of text (“Hello Tutorialwing”) in Material Switch using android:textColor=”” attribute. Similarly, we can set any color using this attribute.
Learn to Set Color of Material Switch Dynamically

Set Gravity of Material Switch

We use android:gravity=”” attribute to set gravity of text in Material Switch.
We can do it as below –

Here, we have set gravity of text in Material Switch using android:gravity=”” attribute. Attribute value can be – “center_horizontal”, “center”, “center_vertical” etc.
Learn to Set Gravity of Material Switch Dynamically

Set Text in Uppercase, Lowercase

If we need to show text of Material Switch in uppercase or lowercase etc.

Set text in uppercase

We can use android:textAllCaps=”true” attribute to set text in uppercase. We can do it as below –

Attribute android:textAllCaps=”true” sets text in uppercase. So, HELLO TUTORIALWING is set in Material Switch.

By default, false is set in this attribute. So, Whatever value is written in android:text=”” attribute, it will be set as it is. For example,

Above code will set Hello Tutorialwing to Material Switch.

How do we set text in lowercase?

  • In xml file – write all the text in lowercase.
  • In kotlin file – take text as string. Then, convert it in lowercase. Then, set it to Material Switch.

Set Size of Text in Material Switch

We use android:textSize=”” attribute to set size of text in Material Switch.
We can do it as below –

Here, we have set size of text in Material Switch using android:textSize=”” attribute.
Learn to Set Size of Text of Material Switch Dynamically

Set Style (Bold/italic) of Text in Material Switch

We use android:textStyle=”” attribute to set style (bold, italic etc.) of text in Material Switch.
We can do it as below –

Here, we have set style of text in Material Switch using android:textStyle=”” attribute. This attribute can take bold, italic or normal.
Learn to Set Style of Text of Material Switch Dynamically

Set Letter Spacing of Text in Material Switch

We use android:letterSpacing=”” attribute to set spacing between letters of text in Material Switch.
We can do it as below –

Here, we have set spacing between letters of text in Material Switch using android:letterSpacing=”” attribute.
Learn to Set Letter Spacing of Text of Material Switch Dynamically

Set Typeface of Text in Material Switch

We use android:typeface=”” attribute to set typeface in Material Switch.
We can do it as below –

Here, we have set typeface of text in Material Switch using android:typeface=”” attribute. This attribute can take values – “sans”, “normal”, “monospace” or “normal”.
Learn to Set Typeface of Material Switch Dynamically

Set fontFamily of Text in Material Switch

We use android:fontFamily=”” attribute to set fontFamily of text in Material Switch.
We can do it as below –

Here, we have set fontFamily (Here, sans-serif) of text in Material Switch using android:fontFamily=”sans-serif” attribute.

Till now, we have see how to use android Material Switch using Kotlin. We have also gone through different attributes of Material Switch to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android Material Switch Widget

Below are the various attributes that are used to customise android Material Switch Widget. However, you can check the complete list of attributes of Material Switch in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –

Some of the popular attributes of Switch widget are –

Sr. XML Attributes Description
1 android:showText It is used to set whether we want to show text(ON/OFF) or not
2 android:textOff Specifies text to show when Switch is in OFF state.
3 android:textOn Specifies text to show when Switch is in ON state.
4 android:textStyle Sets style (bold, italic etc.) of the text.
5 android:thumb It is used to set drawable to be used as thumb that are moved back and forth.
6 android:thumbTextPadding It sets amount of padding on either side of text within the switch thumb.
7 android:thumbTint It is used to set tint to apply to the thumb
8 android:thumbTintMode It is used to set blending mode used to apply the thumb tint
9 android:track It is used to set drawable of the track in which thumb slides back and forth
10 android:typeface Specifies typeface for the text. For example, normal, sans, serif, monospace etc.

Some of the popular attributes of android Switch widget inherited from Compound Button are –

Sr. XML Attributes Description
1 android:button It is used to set drawable to button
2 android:buttonTint It is used to set tint to apply to button tint
3 android:buttonTintMode It is used to set blending mode used to apply to button graphic tint

Some of the popular attributes of android Switch inherited from TextView are –

Sr. XML Attributes Description
1 android:autoLink It is used to decide whether text such as email, url should be automatically detected and converted into links or not.
2 android:cursorVisible It is used to decide whether cursor should be visible or not.
3 android:drawableBottom It is used to set drawable to be shown below text
4 android:ems It is used to set the view be exactly this ems wide

Some of the popular attributes of android Switch inherited from View are –

Sr. XML Attributes Description
1 android:background Sets background
2 android:clickable Decides whether view is clickable or not
3 android:focusable Controls whether a view can take focus or not
4 android:id Id of the view

We have seen different attributes of Material Switch using Kotlin and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is Material Switch, how can we use android Material Switch using Kotlin ? etc. We also went through different attributes of android Material Switch.

Источник

Читайте также:  Как прошить смартфон андроид htc
Оцените статью