Android Custom Implementation Switch button code _android

Source: Internet
Author: User

We often see in the application of the selection of the switch state of the configuration file, the project is to use the Android switch control, but it feels so ugly

Personally think it is better to customize, the first effect chart:


Implementation process:

1. Ready to switch the two pictures in different states into the drawable.

2.xml File Add code:

<togglebutton
android:id= "@+id/switch1"
android:layout_width= "wrap_content"
android:layout_ height= "Wrap_content"
android:layout_gravity= "center"
android:background= "@android: Color/transparent"
android:button= "@drawable/btn_backgrounds"
android:checked= "false"
android:textoff=
"" Android:texton= ""/> 
android:button= "@drawable/btn_backgrounds" is your own definition of the Android selector file: 
< Selector
xmlns:android= "http://schemas.android.com/apk/res/android" >
<item android:state_ Checked= "true" android:drawable= "@drawable/toggle_btn_on"/>

3, then declare the ToggleButton control in the Java file and instantiate it, add the Click event:

/**
* Self created inner class, listener button click event
* 
* @author CYF * *
/
class Myoncheckedchangelistener implements Oncheckedchangelistener {
@Override public
void OnCheckedChanged (Compoundbutton arg0, Boolean arg1) {
if (ARG1) {
//open
} else {//
off}
}

4. Add Listening:

Switch1.setoncheckedchangelistener ((Oncheckedchangelistener) New Myoncheckedchangelistener ());

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.