我有两个整数变量,它们充当计数器和按钮。我还有 2 个链接的切换按钮,因此一次只有 1 个处于活动状态。单击“添加”按钮时,我想根据选中的切换按钮将 1 添加到计数器变量;即如果选中toggle1,则将1添加到counter1
我已经这样尝试过,没有任何乐趣。任何帮助都会很棒。
Counter1= 0;
Counter2= 0;
Add1 = (Button) findViewById(R.id.add1Button);
toggle1 = (ToggleButton) findViewById(R.id.toggle1Button);
toggle2 = (ToggleButton) findViewById(R.id.toggle2Button);
counter1Display= (TextView) findViewById(R.id.count1);
counter2Display= (TextView) findViewById(R.id.count2);
Add1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (toggle1.isChecked()) {
Counter1 += 1;
counter1Display.setText("" + Counter1);
}
if (toggle2.isChecked()) {
Counter2 += 1;
counter2Display.setText("" + Counter2);
}
}
});
这是 LogCat
07-28 11:44:01.156: D/AndroidRuntime(320): Shutting down VM
07-28 11:44:01.156: W/dalvikvm(320): threadid=1: thread exiting with uncaught exception (group=0x40015560)
07-28 11:44:01.176: E/AndroidRuntime(320): FATAL EXCEPTION: main
07-28 11:44:01.176: E/AndroidRuntime(320): java.lang.NullPointerException
07-28 11:44:01.176: E/AndroidRuntime(320): at com.kh.counterapp.MainActivity$2.onClick(MainActivity.java:90)
07-28 11:44:01.176: E/AndroidRuntime(320): at android.view.View.performClick(View.java:2485)
07-28 11:44:01.176: E/AndroidRuntime(320): at android.view.View$PerformClick.run(View.java:9080)
07-28 11:44:01.176: E/AndroidRuntime(320): at android.os.Handler.handleCallback(Handler.java:587)
07-28 11:44:01.176: E/AndroidRuntime(320): at android.os.Handler.dispatchMessage(Handler.java:92)
07-28 11:44:01.176: E/AndroidRuntime(320): at android.os.Looper.loop(Looper.java:123)
07-28 11:44:01.176: E/AndroidRuntime(320): at android.app.ActivityThread.main(ActivityThread.java:3683)
07-28 11:44:01.176: E/AndroidRuntime(320): at java.lang.reflect.Method.invokeNative(Native Method)
07-28 11:44:01.176: E/AndroidRuntime(320): at java.lang.reflect.Method.invoke(Method.java:507)
07-28 11:44:01.176: E/AndroidRuntime(320): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-28 11:44:01.176: E/AndroidRuntime(320): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-28 11:44:01.176: E/AndroidRuntime(320): at dalvik.system.NativeStart.main(Native Method)