android基础二之ToggleButton

//activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.vincentlin.togglebutton.MainActivity" >
 <!-- textOn:true  textOff:false -->
    <ToggleButton
        android:id="@+id/toggleButton1"
        android:checked="false"
        android:textOn="@string/on"
        android:textOff="@string/off"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/off" />
</LinearLayout>
//strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ToggleButton</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="on">开</string>
    <string name="off">关</string>
</resources>
MainActivity.java
package com.vincentlin.togglebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements OnCheckedChangeListener{
 private ToggleButton tButton;
 private ImageView iView;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  //初始化组件
  tButton = (ToggleButton) findViewById(R.id.toggleButton1);
  iView = (ImageView) findViewById(R.id.imageView1);
  /*
   * 给当前的tButton设置监听器
   */
  tButton.setOnCheckedChangeListener(this);
  
 }
 @Override
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  /*
   * 
   * 当tButton被点击的时候,当前的方法会执行
   * buttonView---代表被点击控件的本身,
   * isChecked---代表被点击的控件的状态
   * 当点击这个tButton的时候,更换img的背景
   */
  iView.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);
  
 }
}
//效果图

技术分享

技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。