English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Detailed Explanation of Android ToggleButton
In the process of Android development, the frequency of using ToggleButton is also quite high. Below, I will talk about the two ways of using this component.
The first one is a simple use, which uses Toast to pop up prompt statements
It should be noted that in order to customize the display content of the ToggleButton, you need to set the TextOn and TextOff content.
<ToggleButton android:id="@"+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@"+id/toggleButton2" android:layout_alignBottom="@"+id/toggleButton2" android:textOn="On" android:textOff="Off" android:layout_alignRight="@"+id/imageview" android:text="Simple test" />
Then comes the main display code:
case R.id.toggleButton1: if(SimpleTest.isChecked()){ Toast.makeText(getApplication(), "You have opened the open button", Toast.LENGTH_SHORT).show(); } Toast.makeText(getApplication(), "You have opened the switch button", Toast.LENGTH_SHORT).show(); } break; //It should be noted that the ToggleButton should be declared and initialized first, followed by the registration of event listeners
Next is a more complex usage case, that is, to implement different image display states in cooperation with ImageView
<ToggleButton android:id="@"+id/toggleButton2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@"+id/imageview" android:layout_alignParentTop="true" android:layout_marginTop="46dp" android:textOn="Beautiful" android:textOff="Icon" android:text="With Image" /> <ImageView android:id="@"+id/imageview" android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/note" android:layout_below="@id/toggleButton2" />
Then is the activity code
case R.id.toggleButton2: if(WithImage.isChecked()){ imageview.setImageResource(R.drawable.note); } imageview.setImageResource(R.drawable.ic_launcher); } break;
It should be noted that we also need to declare it first before using it, otherwise an empty pointer error will occur.
Below is the result after the program runs
Summary and Outlook:
Generally speaking, the ToggleButton used during use will not be so simple, but the main idea and framework are still based on here. We can add handling such as muting or status changes in the relevant event listener methods. In this way, our application will become more flexible.