1

单击按钮时,我想选中一个复选框。它给出空指针异常当我运行此代码时,这是我的代码

CheckBox  mCheckBoxRegular = (CheckBox) findViewById(R.id.checkBoxRegular);
Button regular = (Button)findViewById(R.id.buttonRegular);

    regular.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                        mCheckBoxRegular.setChecked(true);

                    }


                }

例外是

08-22 13:24:14.947: E/AndroidRuntime(31390): FATAL EXCEPTION: main
08-22 13:24:14.947: E/AndroidRuntime(31390): java.lang.NullPointerException
08-22 13:24:14.947: E/AndroidRuntime(31390):    at com.example.amazingnumbersample.MainActivity$2$2.onClick(MainActivity.java:128)
08-22 13:24:14.947: E/AndroidRuntime(31390):    at android.view.View.performClick(View.java:3534)
08-22 13:24:14.947: E/AndroidRuntime(31390):    at android.view.View$PerformClick.run(View.java:14263)
08-22 13:24:14.947: E/AndroidRuntime(31390):    at android.os.Handler.handleCallback(Handler.java:605)
08-22 13:24:14.947: E/AndroidRuntime(31390):    at android.os.Handler.dispatchMessage(Handler.java:92)
08-22 13:24:14.947: E/AndroidRuntime(31390):    at android.os.Looper.loop(Looper.java:137)
08-22 13:24:14.947: E/AndroidRuntime(31390):    at android.app.ActivityThread.main(ActivityThread.java:4441)
08-22 13:24:14.947: E/AndroidRuntime(31390):    at java.lang.reflect.Method.invokeNative(Native Method)
08-22 13:24:14.947: E/AndroidRuntime(31390):    at java.lang.reflect.Method.invoke(Method.java:511)
08-22 13:24:14.947: E/AndroidRuntime(31390):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-22 13:24:14.947: E/AndroidRuntime(31390):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-22 13:24:14.947: E/AndroidRuntime(31390):    at dalvik.system.NativeStart.main(Native Method)

请帮我 。

4

2 回答 2

3

我已经尝试了您的代码并进行了一些更改。它似乎按您的意愿工作。

public class MainActivity extends Activity {

    CheckBox mCheckBoxRegular;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mCheckBoxRegular = (CheckBox) findViewById(R.id.checkBox1);

        Button regular = (Button) findViewById(R.id.button1);

        regular.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mCheckBoxRegular.setChecked(true);

            }
        });

    }

}
于 2013-08-22T08:49:06.283 回答
1

尝试这个..!

在你的 setContentView(R.layout.activity);

final CheckBox  mCheckBoxRegular = (CheckBox) findViewById(R.id.checkBoxRegular);
    Button regular = (Button)findViewById(R.id.buttonRegular);

        regular.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                            mCheckBoxRegular.setChecked(true);

                        }


                    });
于 2013-08-22T08:49:54.837 回答