android复选框问题

时间:2011-03-13 08:03:11

标签: android checkbox

我在alertdialog中有这个复选框。当我尝试检查复选框的状态时,应用程序强制关闭。知道为什么吗?

LayoutInflater factory = LayoutInflater.from(NewActivity.this);
        final View textDisplayView = factory.inflate(R.layout.nearestlocs, null);
        final AlertDialog.Builder newAlert = new AlertDialog.Builder(NewActivity.this);
        newAlert.setView(textDisplayView);

        final CheckBox checkBoxLab = (CheckBox) findViewById(R.id.checkboxlab);
newAlert.setPositiveButton("Display on Map",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

                if(checkBoxLab.isChecked()){
                    libDisplayFlag = true;
                }

错误日志

 03-13 08:01:58.273: ERROR/AndroidRuntime(6188): Uncaught handler: thread main exiting due to uncaught exception
    03-13 08:01:58.292: ERROR/AndroidRuntime(6188): java.lang.NullPointerException
    03-13 08:01:58.292: ERROR/AndroidRuntime(6188):     at com.isproj3.NewActivity$3.onClick(NewActivity.java:158)
    03-13 08:01:58.292: ERROR/AndroidRuntime(6188):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:158)
    03-13 08:01:58.292: ERROR/AndroidRuntime(6188):     at android.os.Handler.dispatchMessage(Handler.java:99)

xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout android:orientation="horizontal"
        android:gravity="center" android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:layout_weight="1">
        <CheckBox android:id="@+id/checkboxlib" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="Library"
            android:gravity="left" android:textColor="#FF0000"
            android:paddingBottom="5px" android:textSize="07pt" android:checked="true" />
        <TextView android:id="@+id/librarytext" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:gravity="center"
            android:paddingBottom="5px" android:textSize="8pt" />
    </LinearLayout>
</LinearLayout>

2 个答案:

答案 0 :(得分:1)

我认为问题是你必须指定在哪个视图中找到id

试试这个

final CheckBox checkBoxLab = 
                   (CheckBox) textDisplayView.findViewById(R.id.checkboxlab);

答案 1 :(得分:0)

这个xml实际设置为contenView吗? (所以在此代码之前的某处使用setContetnView()和xml)

否则:

final CheckBox checkBoxLab = (CheckBox) findViewById(R.id.checkboxlab);

会使checkBoxLab成为空指针(null),并且你会得到一个nullPointerException作为原因,有些低于你发布的错误。