Use ToggleButton for picture replacement

Source: Internet
Author: User

1: Add two light bulb pictures in drawable, named Off/on

2:xml file:

<togglebutton
Android:id= "@+id/tbtn"
android:texton= "Open"
Android:textoff= "Off"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"/>
<imageview
Android:id= "@+id/img"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:background= "@drawable/off"/>

3:java file:

protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Initialize the control:
Setcontentview (R.layout.activity_main);
Tbtn= (ToggleButton) Findviewbyid (R.ID.TBTN);
Img= (ImageView) Findviewbyid (r.id.img);
To set up listeners:
Tbtn.setoncheckedchangelistener (this);

public void OnCheckedChanged (Compoundbutton buttonview, Boolean isChecked) {
TODO auto-generated Method Stub
When btnt clicks, the current method executes, Buttonview: represents the clicked control itself, ischecked represents the state of the click Control, and when the button is clicked, the IMG background is replaced
Img.setbackgroundresource (isChecked? R.drawable.on,r.drawable.off);//If clicked, the picture is changed, and the trinocular operator
}

Use ToggleButton for picture replacement

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.