要實現ToggleButton的狀態切換,您可以使用以下方法:
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="開"
android:textOff="關" />
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
private ToggleButton toggleButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton = findViewById(R.id.toggleButton);
// 設置狀態監聽器
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// 當ToggleButton處于選中狀態時執行的操作
Toast.makeText(MainActivity.this, "開", Toast.LENGTH_SHORT).show();
} else {
// 當ToggleButton處于未選中狀態時執行的操作
Toast.makeText(MainActivity.this, "關", Toast.LENGTH_SHORT).show();
}
}
});
}
}
在這個示例中,我們首先在XML布局文件中創建了一個ToggleButton,并設置了文本“開”和“關”。然后,在Activity中,我們通過findViewById()
方法獲取了ToggleButton的引用,并設置了一個狀態監聽器。當ToggleButton的狀態發生變化時,監聽器會調用onCheckedChanged()
方法,我們可以在這個方法中執行相應的操作。