本文實(shí)例講述了Android使用ToggleButton實(shí)現(xiàn)開關(guān)效果的方法。分享給大家供大家參考,具體如下:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ToggleButton android:checked="false" android:textOn="開" android:textOff="關(guān)" android:id="@+id/toggleButton1" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/off" /></LinearLayout>
MainActivity.java
package com.example.hello;import android.support.v7.app.ActionBarActivity;import android.widget.CompoundButton;import android.widget.CompoundButton.OnCheckedChangeListener;import android.widget.ImageView;import android.widget.ToggleButton;import android.os.Bundle;public class MainActivity extends ActionBarActivity implements OnCheckedChangeListener { private ToggleButton tb; private ImageView img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化控件 tb = (ToggleButton) findViewById(R.id.toggleButton1); img = (ImageView) findViewById(R.id.imageView1); //給當(dāng)前的tb設(shè)置監(jiān)聽器 tb.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { /* * 當(dāng)tb被點(diǎn)擊的時(shí)候,執(zhí)行當(dāng)前方法 * buttonView 代表被點(diǎn)擊的控件本身 * isChecked 代表被點(diǎn)擊的控件的狀態(tài) * * 當(dāng)點(diǎn)擊tb的時(shí)候,更換img的背景 */ img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off); }}
希望本文所述對大家Android程序設(shè)計(jì)有所幫助。
|
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注