Android control-ToggleButton

Source: Internet
Author: User

The ToggleButton status can only be selected or not selected, and different display text needs to be set for different states.

The following uses ToggleButton:

Directory structure

Main. xml layout File

<? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent">
<ImageView android: id = "@ + id/imageView"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: src = "@ drawable/bulb_off"
Android: layout_gravity = "center_horizontal"/>
<ToggleButton android: id = "@ + id/toggleButton"
Android: layout_width = "140dip"
Android: layout_height = "wrap_content"
Android: textOn = "turn on the light"
Android: textOff = "turn off the light"
Android: layout_gravity = "center_horizontal"/>
</LinearLayout>

ToggleButtonActivity class

package com.ljq.tb;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class ToggleButtonActivity extends Activity {
private ImageView imageView=null;
private ToggleButton toggleButton=null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

imageView=(ImageView) findViewById(R.id.imageView);
toggleButton=(ToggleButton)findViewById(R.id.toggleButton);
toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener(){

public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
toggleButton.setChecked(isChecked);
imageView.setImageResource(isChecked?R.drawable.bulb_on:R.drawable.bulb_off);
}

});
}
}

Running effect:

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.