標籤: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); }}
//
650) this.width=650;" style="float:none;" title="映像 off.png" src="http://s3.51cto.com/wyfs02/M01/58/A2/wKiom1S2IPLhSXq_AADbiGquCTE871.jpg" alt="wKiom1S2IPLhSXq_AADbiGquCTE871.jpg" />
650) this.width=650;" style="float:none;" title="映像 on.png" src="http://s3.51cto.com/wyfs02/M02/58/9F/wKioL1S2IcChB0wlAADySSar6V4214.jpg" alt="wKioL1S2IcChB0wlAADySSar6V4214.jpg" />
android基礎二之ToggleButton