What is toggle button in android

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 Buttons

In the previous lessons, we added RadioButtons and CheckBoxes to a layout, and wrote the code to get them working. Another widget we can add to your apps is the Toggle button. This lets you have an on/off state. What we’ll do is to add one to our layout for Terms and Conditions. If the Toggle button is off then the user doesn’t agree with the Terms and Conditions. If the button is on, then they do agree with them. Let’s see how they work. We’ll also explore listeners.

In earlier versions of Android Studio, click on the Widgets category in your palette. Locate the ToggleButton item:

In later versions, the ToggleButton is in the Buttons category:

Drag one on to your layout and position it under the checkboxes. Add constraints to the top of the toggle button to the bottom of the third checkbox. You can also add constraints to the left end right edges of the screen, and the bottom of the screen. Your layout should look something like this:

With the toggle button selected, have a look at the ID property on the right. It has a default ID of toggleButton. Change this to termsToggle:

In later versions of Android Studio, expand the Lalyout item to see the constraints section:

Now open up your MainActivity.java file.

Previously, we set up methods to handle our button presses. We then pointed to the methods using the properties area. Another way to handle button presses and clicks is to set up something called a Listener. As the name suggests, these Listeners listen out for any button presses or clicks. They then call a method that activates your code. When you set up a Listener, you don’t need to use the properties area to point to a method. A Listener is always alert and ready for action!

Listeners are usually set up in the onCreate method of your app. This way, they are initialised when the app starts up. This contrasts with the methods we set up before, where the method has to be initialised and called when a button is pressed or clicked.

In the onCreate method of your code, then, add the following line:

final ToggleButton myToggle = (ToggleButton) findViewById(R.id.termsToggle);

(If you get any red text, press ALT + Enter to add the android library for a ToggleButton. Or simply type import android.widget.ToggleButtton; to the top of your code.)

The line of code just sets up a ToggleButton with the variable name of myToggle. We use findViewById to reference the toggle button on the layout.

To set up the listener, you start with this rather complicated code:

myToggle.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() <

Note where all the curly brackets and round brackets are. It’s very easy to get these wrong! At the end, you need a curly bracket, a round bracket, and a semicolon.

Читайте также:  Сервер samp для android

You’re not done setting up the listener yet, though. Add this method inside of the listener. It should get rid of any red lines you have:

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) <

The whole thing should look like this:

If you’re missing any import statements at the top for this project, you should have these (the ones in bold are new for this tutorial):

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.ToggleButton;

The actual code for the listener is fairly simply. It’s this:

TextView myText = (TextView) findViewById(R.id.displayArea);

myText.setText(«I agree with the Terms and Conditions»);

myText.setText(«I do NOT agree with the Terms and Conditions»);

Again, we get a reference to our TextView called displayArea. Then we have an IF statement. The IF statement examines a boolean variable called isChecked. If this is true then we set some text; if it’s false then we set some other text. But where is this Boolean variable isChecked coming from? Well, have a look at the method inside of the listener:

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) <

The onCheckedChanged method accepts a Boolean variable as one of its parameters. It’s this Boolean variable, isChecked, that is used in our code.

Add the if statement to your own code and your onCreate method will look like this (the highlighted text is because we didn’t set up a string resource, but simply entered text directly):

Test out your app. When you run it on the Emulator or a real phone hit your toggle button. You should see this:

Hit the toggle button again and you’ll see this:

So we’re toggling from ON to OFF, with a different message being displayed, depending on which state the toggle button is in.

That text on the toggle button that says ON and OFF can be changed to something of your choosing. Stop the app from running. In Android Studio, click back on the activity_main.xml file. Make sure you are in Design view and not Text view for the layout. With your toggle button selected, look at the properties area on the right. Locate the textOff and textOn properties. Here they are in earlier versions of Android Studio:

In later versions, you need to expand the Common Attributes section:

Change these to anything you like (again, we’re entering direct text rather than setting up a string resource):

Now run your app again. You should see this for the toggle button off state when the app first loads:

And this for the ON state:

You can even set these values with code, if you want to. Like this:

final ToggleButton myToggle = (ToggleButton) findViewById(R.id.termsToggle);

The two method to use are setTextOn and setTextOff.

ToggleButton styles

If you don’t like the style of your toggle button, you can choose one of the other presets quite easily. In Design Layout view, click on your toggle button to select it. In the properties area on the right, locate the style property and click the button to the right of the textbox:

Clicking the button brings up the Resources dialogue box. Type toggle in the search box at the top to see the following styles you can apply:

Select one of the styles under the Android heading. In the image below, we’ve gone for Widget.Button.Toggle:

When the app is run, the toggle button will look like this in the ON state:

Try some of the other styles, though, to see what they look like.

In the next lesson, you’ll learn about the Android SeekBar. A SeekBar is one of those sliders you use to change the brightness or volume on your phone/tablet.

Источник

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)
Читайте также:  Android list avd devices

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 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.

Читайте также:  Gsm and wcdma android

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.

Источник

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