ToggleButton有兩種狀態:選中和未選中狀態java
而且須要爲不一樣的狀態設置不一樣的顯示文本android
android:checked="true"ide
android:textOff="關"spa
android:textOn="開"code
3.代碼xml
<!--activity_main.xml--> <ToggleButton android:id="@+id/ToggleButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:textOff="關" android:textOn="開" android:checked="false"/> <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/ToggleButton" android:background="@drawable/close"/>
//MainActivity.java public class MainActivity extends AppCompatActivity { 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); //給當前的tb設置監聽 tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { /** * 當tb被點擊的時候,當前的方法會執行 * * compoundButton -- 表明被點擊控件的自己 * b -- 表明被點擊的控件的狀態 * * 當點擊這個tb的時候,更換img的背景 */ img.setBackgroundResource(b?R.drawable.light:R.drawable.close); } }); } }
效果以下:it