我正在尝试将复选框编码到帮助屏幕中,该屏幕本质上是一个弹出视图(由主程序启动的活动),其中包含一个具有帮助文本的 ScrollView、确定按钮和一个询问您是否想要的复选框帮助屏幕在程序启动时自动出现。一切都在屏幕上正确显示,并且复选框在触摸时切换。但是,当按下 OK 并使用 .isChecked() 测试复选框的状态时,我总是得到一个错误。我敢肯定这是我错过的简单事情。XML 文件如下:
帮助对话框.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:background="#ffffff">
<ScrollView android:id="@+id/ScrollView01"
android:layout_width="wrap_content" android:layout_below="@+id/ImageView01"
android:layout_height="300px">
<TextView android:text="@+id/helpView" android:id="@+id/helpView"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textColor="#000000"/>
</ScrollView>
<Button android:id="@+id/Button01"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_centerHorizontal="true" android:text=" OK "
android:layout_below="@id/ScrollView01"/>
<CheckBox android:id="@+id/chkNoHelp" android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Don't Display at Startup"
android:layout_below="@id/Button01" />
</RelativeLayout>
帮助框.java:
public class HelpBox extends Activity {
CheckBox checkBox;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set up dialog
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.helpdialog);
dialog.setTitle("Help");
dialog.setCancelable(true);
//set up text
TextView text = (TextView) dialog.findViewById(R.id.helpView);
text.setText(getString(R.string.help_text));
//set up button
Button button = (Button) dialog.findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Boolean mDisplayHelp;
setContentView(R.layout.helpdialog);
checkBox = (CheckBox) findViewById(R.id.chkNoHelp);
if (checkBox.isChecked()) {
mDisplayHelp = true;
} else {
mDisplayHelp = false;
}
finish();
}
});
//now that the dialog is set up, it's time to show it
dialog.show();
}
}
在“mDisplayHelp”行上设置断点总是在“false”分支处中断,无论按下 OK 按钮时复选框是否显示绿色复选标记。
提前致谢。
编辑(10/10):
很明显我想要做的是在用户退出对话框后获取信息,这样我就可以感知复选框的状态并将其存储为首选项。为此,我假设我必须在 onDestory 中对其进行测试。所以,我这样做了:
@Override
public void onDestroy() {
Boolean mDisplayHelp;
setContentView(R.layout.helpdialog);
checkBox = (CheckBox) findViewById(R.id.chkNoHelp);
if (checkBox.isChecked()) {
mDisplayHelp = true;
} else {
mDisplayHelp = false;
}
}
但是,无论复选框是选中还是关闭,我仍然总是想出 FALSE。在这种情况下,如果我不包含 setContentView,我会在 isChecked 上得到 NullPointerException。