什么是ToggleButton?
ToggleButton一般有兩種狀態(tài):選中和未選中
并且需要為不同狀態(tài)設(shè)置不同的文本
ToggleButton屬性
android:checked=”true”——當(dāng)前按鈕狀態(tài),選中為”true”,未選中為”false”
android:textOn=”開”
android:checked=”true”的時候,顯示 取決于checked的狀態(tài),即當(dāng)checked=”true”的時候,顯示textOn=”開”,當(dāng)checked=”false”的時候,顯示checked=”true”
先來看一下實(shí)現(xiàn)效果:

具體代碼
<ToggleButton android:checked="false" android:id="@+id/toggleButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:textOn="開" android:textOff="關(guān)" /> <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/off" />
package com.example.admin.demo;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.widget.CompoundButton;import android.widget.ImageView;import android.widget.ToggleButton;public class MainActivity extends AppCompatActivity implements CompoundButton.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.toggleButton); img = (ImageView) findViewById(R.id.imageView1); //設(shè)置監(jiān)聽器 tb.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { img.setImageResource(isChecked?R.drawable.on:R.drawable.off); }}以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選