在Android开发中,切换按钮(ToggleButton或Switch)是常用的UI控件,用于在两个状态之间切换。调用新活动(Activity)是Android应用导航的基本方式之一。
// 在Activity中
ToggleButton toggleButton = findViewById(R.id.toggleButton);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// 当按钮被选中时启动新Activity
Intent intent = new Intent(MainActivity.this, NewActivity.class);
startActivity(intent);
}
}
});
// 在Activity中
Switch switchButton = findViewById(R.id.switchButton);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// 当开关打开时启动新Activity
Intent intent = new Intent(MainActivity.this, NewActivity.class);
startActivity(intent);
}
}
});
首先在res/layout/activity_main.xml中添加切换按钮:
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="关闭"
android:textOn="打开" />
或者使用Switch:
<Switch
android:id="@+id/switchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开关" />
Switch switchButton = findViewById(R.id.switchButton);
switchButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
Intent intent = new Intent(MainActivity.this, NewActivity.class);
intent.putExtra("switch_state", isChecked); // 传递参数
startActivity(intent);
}
});
在NewActivity中接收参数:
boolean switchState = getIntent().getBooleanExtra("switch_state", false);
问题1:点击切换按钮后Activity启动多次
问题2:返回后按钮状态不正确
问题3:新Activity未启动
没有搜到相关的文章