【发布时间】:2021-12-16 05:50:46
【问题描述】:
如何找出切换按钮崩溃的原因?
我的切换按钮在更改其状态时崩溃。我的情况:如果我将切换按钮的状态从 Off 更改为 On 突然,整个应用程序崩溃并显示“YourApp is not Responding”。我不知道代码中的错误是什么。我是 Android 应用程序开发的新手。所以,我不知道如何找到并纠正错误。如果有人知道请在我的情况下帮助我。提前致谢!
这是我的代码:
这是我的 XML 文件:
<ToggleButton
android:id="@+id/toggle_button"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_marginTop="-2dp"
android:layout_marginLeft="-45dp"
android:background="@drawable/toggle_selector"
android:textOff=""
android:textOn="" />
这是我的 Java 代码:
/*------------------------------Screen timeout toggle----------------------------------------------------*/
ToggleButton toggle_button = (ToggleButton) findViewById(R.id.toggle_button);
toggle_button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
try {
if (isChecked) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
timeout_on = Toast.makeText(getBaseContext(), "Screen Timeout is Disabled (Your screen will doesn't sleep from now!)", Toast.LENGTH_LONG);
TextView v = (TextView) timeout_on.getView().findViewById(android.R.id.message);
if( v != null) v.setGravity(Gravity.CENTER);
timeout_on.show();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
timeout_off = Toast.makeText(getBaseContext(), "Screen Timeout is Enabled (Your screen will go to sleep as your phone's timeout!)", Toast.LENGTH_LONG);
TextView v = (TextView) timeout_off.getView().findViewById(android.R.id.message);
if( v != null) v.setGravity(Gravity.CENTER);
timeout_off.show();
}
} catch (Exception error) {
error.printStackTrace();
}
}
});
/*------------------------------Screen timeout toggle----------------------------------------------------*/
【问题讨论】:
标签: java android-studio button android-togglebutton