您好,登錄后才能下訂單哦!
//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/p_w_picpathView1" 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">關(guān)</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.p_w_picpathView1); /* * 給當前的tButton設(shè)置監(jiān)聽器 */ tButton.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { /* * * 當tButton被點擊的時候,當前的方法會執(zhí)行 * buttonView---代表被點擊控件的本身, * isChecked---代表被點擊的控件的狀態(tài) * 當點擊這個tButton的時候,更換img的背景 */ iView.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off); } }
//效果圖
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。