Android ToggleButton, Switch, CheckBox, RadioButton controls

Table of Contents

ToggleButton

concept

renderings

Code

Switch

concept

renderings

CheckBox

concept

renderings

Code

RadioButton

concept

renderings

Code


ToggleButton

Concept

ToggleButton is a basic control in Android. It can switch between two states and is often used to represent functions such as switching and enabling/disabling.

Some important features and usage of ToggleButton:

  1. Layout: In an XML layout file, you can use the tag to create a ToggleButton. You can set its text, style, size, color and other properties, and assign it a unique ID.

  2. Switch state: ToggleButton has two states, namely selected state and unselected state. The user can toggle its state by clicking on the ToggleButton. The initial state can be specified by setting the setChecked() method.

  3. Monitoring status changes: You can monitor status changes by setting the OnCheckedChangeListener interface for ToggleButton. When the state of ToggleButton changes, the corresponding callback method will be triggered, and the corresponding operations can be performed in the callback method.

  4. Get status: You can use the isChecked() method to get the current status of ToggleButton. If true is returned, it indicates the selected state; if false is returned, it indicates the unselected state.

  5. Custom styles: You can change the appearance and behavior of ToggleButton by customizing its style. You can use properties and styles to modify its background, text color, size, icons, etc. to suit your design needs.

  6. Application scenarios: ToggleButton is often used for functions that require switching status, such as enabling/disabling a certain setting, turning on/off a certain function, switching view display modes, etc. It provides an intuitive user interface element to facilitate users to perform status switching operations.

Rendering

Using this logic, the following renderings can also be achieved

Code Implementation

 <!-- xml file -->

    <ToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@ + id/toggleButton"
        android:textOn="on state"
        android:textOff="off state" />
public class MainActivity extends AppCompatActivity implements View.OnClickListener ,CompoundButton.OnCheckedChangeListener{
    private static final String TAG = "MainActivity";
    ToggleButton toggleButton;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("MainActivity","onCreate execute");

        toggleButton = findViewById(R.id.toggleButton);
       
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isCheck) {
                if(isCheck)
                    System.out.println();
                else
                    System.out.println();
            }
        });
        

Switch

Concept

The Switch control is a switch button control provided by the Android platform for representing one of two states. It is usually used in user interfaces that need to represent functions between two states, such as switching an option on and off, enabling or disabling a function, etc.

The Switch control provides a slider (Thumb) and a background track (Track) to represent switching between two states. The slider can slide horizontally and switch the status of the switch according to the user’s operation. When the slider is on the left, it indicates an off state, and when the slider is on the right, it indicates an on state.

Commonly used attributes of Switch include

android:typeface=”normal”:Set font type
android:track=””:Set the track image of the switch
android:textOff=”on”: Set the text of the switch checked
android:textOn=”off”: Set the text when the switch is turned off
android:thumb=””: Picture of setting switch
android:switchMinWidth=””: switch minimum width
android:switchPadding=””: Set the blank distance between the switch and the text
android:switchTextAppearance=””:Set the text style
android:checked=””: Set the initial checked state
android:splitTrack=”true”: Whether to set a gap to separate the slider from the bottom image (API 21 and above)
android:showText=”true”: Set whether to display the text on the switch (API 21 and above)

Rendering

Code implementation

<!--xml file-->

    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@ + id/switch_"
        android:layout_margin="10dp"
        android:textColor="#fff"
        android:typeface="normal"
        android:switchMinWidth="60dp"
        android:switchPadding="10dp"
        android:showText="true"
        android:textOn="on"
        android:textOff="off"
        android:track="@drawable/switch_track"
        android:thumb="@drawable/switch_thumb"/>

switch_track.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape android:shape="rectangle">
            <solid android:color="#7FFFD4"/>
            <stroke android:width="3dp"
                android:color="#00000000"/>
            <corners android:radius="15dp"/>
            <size android:height="32dp"/>
        </shape>
    </item>
    <item android:state_checked="false">
        <shape android:shape="rectangle">
            <solid android:color="#B6B6B4" />
            <stroke android:width="3dp"
                android:color="#00000000"/>
            <corners android:radius="15dp"/>
            <size android:height="32dp"/>
        </shape>
    </item>
</selector>

switch_thumb.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape android:shape="oval">
            <size
                android:width="32dp"
                android:height="32dp"/>
            <solid android:color="#D1D0CE"/>
        </shape>
    </item>
    <item android:state_checked="false">
        <shape android:shape="oval">
            <size
                android:width="32dp"
                android:height="32dp"/>
            <solid android:color="#D1D0CE"/>
        </shape>
    </item>
</selector>
public class MainActivity extends AppCompatActivity implements View.OnClickListener ,CompoundButton.OnCheckedChangeListener{
   
    Switch aSwitch;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("MainActivity","onCreate execute");

        aSwitch = (Switch) findViewById(R.id.switch_);
      
        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean check) {
                if(check)
                    System.out.println("switch is checked!");
                else
                    System.out.println("switch is not checked!");
            }
        });

CheckBox

Concept

CheckBox is a common user interface control provided by the Android platform, used to represent multi-select or radio-select options.

The CheckBox control usually takes the form of a box and a selectable mark (tick). Users can select or deselect options by clicking on the CheckBox. Unlike the Switch control, the CheckBox control can represent the status of multiple options, not just the switching of two states.

Rendering

Code implementation

<!--xml file-->
<CheckBox
        android:id="@ + id/banana"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Banana"
        android:textSize="30sp">
    </CheckBox>

    <CheckBox
        android:id="@ + id/apple"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Apple"
        android:textSize="30sp">
    </CheckBox>

    <CheckBox
        android:id="@ + id/strawberry"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Strawberry"
        android:textSize="30sp">
    </CheckBox>
public class MainActivity extends AppCompatActivity implements View.OnClickListener ,CompoundButton.OnCheckedChangeListener{
    private static final String TAG = "MainActivity";

    CheckBox cb1;
    CheckBox cb2;
    CheckBox cb3;
    Button btn_send;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("MainActivity","onCreate execute");

        cb1 = (CheckBox) findViewById(R.id.banana);
        cb2 = (CheckBox) findViewById(R.id.apple);
        cb3 = (CheckBox) findViewById(R.id.strawberry);

    @Override
    public void onClick(View view) {
        String choose = " ";
        if(cb1.isChecked())
            choose + = cb1.getText().toString() + " ";
        if (cb2.isChecked())
            choose + = cb2.getText().toString() + " ";
        if(cb3.isChecked())
            choose + = cb3.getText().toString() + " ";
        Toast.makeText(this,choose,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if(compoundButton.isChecked())
                                                    Toast.makeText(this,compoundButton.getText().toString(),Toast.LENGTH_LONG).show();
    }
}

RadioButton

Concept

RadioButton (radio button) is one of the basic controls in Android. It is a button with two states (selected and unselected). In a group of RadioButtons, only one option can be selected. Selecting one RadioButton will automatically cancel the selection state of other RadioButtons.

The following are some important features and usage of RadioButton:

  1. Layout: In an XML layout file, you can use the tag to create a RadioButton. You can set its text, style, size, color and other properties, and assign it a unique ID.

  2. Radio group: In order to ensure that only one option can be selected in a group of RadioButtons, they need to be placed in the same RadioGroup. RadioGroup is a container that manages the RadioButtons in it and automatically handles the logic of selecting and unchecking.

  3. Checked state: RadioButton can be set to the selected state by setting its setChecked(true) method. When the user clicks on a RadioButton, it is automatically selected and unchecks other RadioButtons.

  4. Listening to selected events: You can listen to changes in the selected status by setting the OnCheckedChangeListener interface for RadioButton. When the selected state of RadioButton changes, the corresponding callback method will be triggered, and corresponding operations can be performed in the callback method.

  5. Get the selected item: The ID of the currently selected RadioButton can be obtained through the getCheckedRadioButtonId() method of RadioGroup. Further, you can get the selected RadioButton through this ID, and get its text or other properties.

  6. Custom styles: You can change the appearance and behavior of a RadioButton by customizing its style. You can use properties and styles to modify its background, text color, size, icons, etc. to suit different design needs.

RadioButton is widely used in applications where you need to choose from multiple mutually exclusive options, such as gender selection, tab switching, questionnaires, etc. It provides a simple and intuitive user interface element to facilitate users to perform single selection operations.

Renderings

This is very similar to our CheckBox. The difference is that this control can be converted from an unselected state to a selected state through a click event, but cannot achieve the reverse state transition through a click. A default style The unselected and selected states of the RadioButton control are as follows:

Code Implementation

Need to use RadioGroup to achieve

<!--xml file-->
<RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@ + id/radioGroup">
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@ + id/r1"
            android:layout_margin="10dp"
            android:text="I am Eddie Peng"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@ + id/r2"
            android:layout_margin="10dp"
            android:text="I am Daniel Wu"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@ + id/r3"
            android:layout_margin="10dp"
            android:text="I am Louis Koo"/>
    </RadioGroup>
public class MainActivity extends AppCompatActivity implements View.OnClickListener ,CompoundButton.OnCheckedChangeListener{
    private static final String TAG = "MainActivity";
    
    RadioButton radioButton1;
    RadioButton radioButton2;
    RadioButton radioButton3;
    RadioGroup radioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("MainActivity","onCreate execute");

        radioButton1 = (RadioButton) findViewById(R.id.r1);
        radioButton2 = (RadioButton) findViewById(R.id.r2);
        radioButton3 = (RadioButton) findViewById(R.id.r3);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.r1)
                    System.out.println();
            }
        });
}