- ToggleButton (Кнопка-переключатель)
- Общая информация
- Стилизация
- Android toggle button example
- Android Toggle Button
- Toggle Button Element
- Toggle Button Default Style
- Toggle Button Custom Style
- Individual Toggle Button Custom Style
- Toggle Button Text
- Toggle Button Click Event Handling
- Custom Toggle Button
- Custom toggle button drawable xml
- Custom toggle button color selector
- Custom toggle button output
- Toggle Button Image
- About
- Android ToggleButton example
- 1. Custom String
- 2. ToggleButton
- 3. Code Code
- 4. Demo
- Download Source Code
- References
- Comments
- Android Toggle Button with Examples
- Create ToggleButton in XML Layout File
- Create ToggleButton Control in Activity File
- Handle Android ToggleButton Click Events
- Android ToggleButton Control Attributes
- Android ToggleButton Control Example
- activity_main.xml
- MainActivity.java
- Output of Android ToggleButton Example
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 toggle button example
Android Toggle Button
September 15, 2017
Toggle button represents two states and state changes between on and off every time ToggleButton is clicked. Like CheckBox, it can be used to capture input for two state input fields.
In this post, I’ll show how to style toggle button, create custom styles for it, and customize toggle button by setting custom background and button.
Toggle Button Element
Toggle Button Default Style
Below screen shot shows toggle button in on and off state with default material style when application theme is set to material theme Theme.AppCompat.
Toggle Button Custom Style
You can customize appcompact material theme to change Toggle button colors. You can customize toggle button text color, toggle button on color, toggle button off color, toggle button normal color, toggle button highlight color by setting textColorPrimary, colorAccent, colorControlNormal, colorButtonNormal, and colorControlHighlight color attributes respectively in your custom theme. Apply the defined custom theme at application level by setting theme attribute of application element in manifest xml file.
Individual Toggle Button Custom Style
Above toggle button customization was done at application theme level. Customizing colors at application level impacts not only all toggle buttons but also other ui controls in your application.
If you want to customize particular toggle buttons, you can create custom style by inheriting toggle button material theme Widget.Material.Light.Button.Toggle and setting required properties as shown below.
Toggle Button Text
Toggle button text can be change by setting testOn and textOff attributes in xml or code. Below xml code and screenshot show textOn and textOff attribute setting and its output.
Toggle Button Click Event Handling
Toggle button event can be handled by adding CompoundButton.OnCheckedChangeListener to it using setOnCheckedChangeListener method as shown below. Using isChecked parameter passed to onCheckedChanged method, you can get toggle state of toggle button.
Custom Toggle Button
You can create custom toggle button by defining xml drawable and using it as background of toggle button by setting background attribute to it. Since color of lines of toggle button need to change based on the check state, a selector is defined for it.
Custom toggle button drawable xml
Custom toggle button color selector
Custom toggle button output
Toggle Button Image
You can customize toggle button by creating image selector drawable and setting it as button for ToggleButton.
To customize toggle button this way, you need to provide your own images for two states. In order for the custom button to appear properly, you need to provide different sizes of images for different screen sizes by saving them in the appropriate size specific drawable folders and also set ToggleButton layoutWidth and layoutHeight to match image size.
About
Android app development tutorials and web app development tutorials with programming examples and code samples.
Источник
Android ToggleButton example
By mkyong | Last updated: August 29, 2012
Viewed: 215,257 (+8 pv/w)
In Android, the “android.widget.ToggleButton” is a special class to render a button which has only two states, for example, “on and “off”. It’s best alternative to radio buttons to turn on or turn off a function.
In this tutorial, we show you how to use XML to create two toggle buttons and a normal button, when user click on the normal button, it will display the current state of both toggle buttons.
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.
1. Custom String
Open “res/values/strings.xml” file, add some custom string for toggle buttons.
2. ToggleButton
Open “res/layout/main.xml” file, add two “ToggleButton” and a normal button, inside the LinearLayout .
3. Code Code
Inside activity “ onCreate() ” method, attach a click listeners on a normal button, to display the current state of the toggle button.
4. Demo
Run the application.
1. Result, toggleButton2 is using the customized string, and checked by default.
2. Checked toggleButton1 and unchecked toggleButton2, and click on the display button, the current state of both toggle buttons will be displayed.
Download Source Code
References
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.
Comments
Why do we need another button to display the state of toggle button this is ridiculous. Why can’t just the state on toggle view being clicked itself.
You can consider the button to display as a summary of states before their saves, by imagining the case you would have several toggle buttons. What would happen if you change the state of some of these buttons and after you decide to cancel your changes ?
If the state was saved when changing the corresponding toggle button, you would have to remember what was its initial state.
Is it me or everyone else also think that it is confusing ? one button could have done the thing . why complicate it ?
I have struggled with this lesson for a while, after playing around I discovered that setContentView (R.layout.main); in MyAndroidAppActivity.java was messing up my application. I have blanked this out and now my app is running for the first time. Obviously I do not get anything back if I press the Display button on the app now. Hope this helps someone, please give advice I you want to. Regards Louwrens van Deventer (South Africa)
its confusing and is more confusing when doing on android studio..iam beginner with a little knowledge
please send me Google map source code in android in simple code.
please my question not about this lesson but i use android for hand gesture recognition and dont have any idea about what i can do please can u help if u know or any body have any idea
[…] Complete tutorial you can get it here: Android toggle button example. […]
[…] use ToggleButton. numerous examples available like here. […]
Thanks for this Android ToggleButton example! I compiled a list of some top resources I found on creating toogle buttons in android. I included you post. Check it out/ free to share. http://www.verious.com/board/Giancarlo-Leonio/creating-a-toggle-button-in-android/ Hope other developers find this useful too. рџ™‚
was not working.why?
Instead of this, you can use:
Toast.makeText(this, result.toString(),Toast.LENGTH_SHORT).show();
you can use this instead of buffer:-
Toast.makeText(getApplicationContext(),toggleButton1 .getText() +”\n” + toggleButton2.getText() , Toast.LENGTH_LONG).show();
Buttons are quite ugly!
[…] Android toggle button example Use “ToggleButton” to render a button which has only two states (On and Off). […]
These statements have no effect on visibility of the ToggleButton view.
Thanks for your input!
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ActtoActActivity extends Activity <
/** Called when the activity is first created. */
@Override
Источник
Android Toggle Button with Examples
In android, Toggle Button is a user interface control that is used to display ON (Checked) or OFF (Unchecked) states as a button with a light indicator.
The ToggleButton is useful for the users to change the settings between two states either ON or OFF. We can add a ToggleButton to our application layout by using the ToggleButton object.
Following is the pictorial representation of using ToggleButton in android applications.
By default, the android ToggleButton will be in OFF (Unchecked) state. We can change the default state of ToggleButton by using android:checked attribute.
In case, if we want to change the state of ToggleButton to ON (Checked), then we need to set android:checked = “true” in our XML layout file.
In android, we can create ToggleButton control in two ways either in the XML layout file or create it in the Activity file programmatically.
Create ToggleButton in XML Layout File
Following is the sample way to define ToggleButton control in XML layout file in android application.
If you observe above code snippet, here we defined ToggleButton control and setting ToggleButton state ON using android:checked attribute in xml layout file.
Create ToggleButton Control in Activity File
In android, we can create ToggleButton control programmatically in activity file based on our requirements.
Following is the example of creating ToggleButton control dynamically in the activity file.
RelativeLayout layout = (RelativeLayout)findViewById(R.id. r_layout );
ToggleButton tb = new ToggleButton( this );
tb.setTextOff( «OFF» );
tb.setTextOn( «ON» );
tb.setChecked( true );
layout.addView(tb);
This is how we can define ToggleButton in XML layout file or programmatically in activity file based on our requirements.
Handle Android ToggleButton Click Events
Generally, whenever the user clicks on ToggleButton, we can detect whether ToggleButton is in ON or OFF state and we can handle the ToggleButton click event in activity file using setOnCheckedChangeListener like as shown below.
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.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 ToggleButton click events in android applications based on our requirements.
Android ToggleButton Control Attributes
The following are some of the commonly used attributes related to ToggleButton 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 toggle button |
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 the toggle button is in the OFF / Unchecked state. |
android:textColor | It is used to change the color of text. |
android:textSize | It is used to specify the size of 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 drawable to be drawn to the below text. |
android:drawableRight | It’s drawable to be drawn to the right of the text. |
android:drawableLeft | It’s drawable to be drawn to the left of text. |
Android ToggleButton Control Example
Following is the example of defining two ToggleButton controls and one Button control in RelativeLayout to get the state of ToggleButton controls when we click on Button control in the android application.
Create a new android application using android studio and give names as ToggleButtonExample. 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» >
ToggleButton
android :id= «@+id/toggle1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :layout_marginTop= «120dp»
android :checked= «true»
android :textOff= «OFF»
android :textOn= «ON»/>
ToggleButton
android :id= «@+id/toggle2»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_alignBottom= «@+id/toggle1»
android :layout_toRightOf= «@+id/toggle1»
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= «Submit»/>
RelativeLayout >
If you observe above code we defined a two ToggleButton controls and one Button control in RelativeLayout to get the state of ToggleButton controls when we click on Button control 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.togglebuttonexample path and write the code like as shown below.
MainActivity.java
package com.tutlane.togglebuttonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity <
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
final ToggleButton tb1 = (ToggleButton)findViewById(R.id. toggle1 );
final ToggleButton tb2 = (ToggleButton)findViewById(R.id. toggle2 );
Button btnGet = (Button)findViewById(R.id. getBtn );
btnGet.setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
Toast.makeText(getApplicationContext(), «Toggle Button1 — » + tb1 .getText().toString() + » \n » + «Toggle Button2 — » + tb2 .getText().toString(),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 the state of two ToggleButton controls on Button click.
Generally, during the launch of our activity, the onCreate() callback method will be called by android framework to get the required layout for an activity.
Output of Android ToggleButton Example
When we run above example using an android virtual device (AVD) we will get a result like as shown below.
This is how we can use ToggleButton control in android applications to switch the settings between two states either ON or OFF based on our requirements.
Источник