(圖片來源慕課網)
Demo效果:
activity_main.xml代碼:
<ToggleButton
android:id="@+id/toggle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textOff="關"
android:textOn="開" />
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Java代碼:public class MainActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener {
private ToggleButton tb;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tb = (ToggleButton) findViewById(R.id.toggle);
iv = (ImageView) findViewById(R.id.iv);
tb.setOnCheckedChangeListener(this);//監聽器
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
iv.setBackgroundColor(isChecked?Color.BLACK:Color.WHITE);//非黑即白
}
}