use*_*048 0 android android-widget android-layout
我有一个复选框和一个textView,当选中复选框时,textview应显示该复选框被按下.但是当我运行我的代码时,我得到一个nullpointerexception.这是我的代码:
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
CheckBox android=(CheckBox)findViewById(R.id.android);
CheckBox ios=(CheckBox)findViewById(R.id.ios);
CheckBox webos=(CheckBox)findViewById(R.id.webos);
CheckBox windows=(CheckBox)findViewById(R.id.windows);
Button generate=(Button)findViewById(R.id.generate);
final TextView result=(TextView)findViewById(R.id.result);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
android.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(((CheckBox)view).isChecked())
result.setText("Android Checked");
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的问题所在的logcat的一部分:
12-21 17:25:00.324: ERROR/AndroidRuntime(960): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.GridAndroid/com.example.GridAndroid.MyActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.GridAndroid.MyActivity.onCreate(MyActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
Run Code Online (Sandbox Code Playgroud)
所以我的问题是我的代码有什么问题?
在setcontentview()之后获取id
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CheckBox android=(CheckBox)findViewById(R.id.android);
CheckBox ios=(CheckBox)findViewById(R.id.ios);
CheckBox webos=(CheckBox)findViewById(R.id.webos);
CheckBox windows=(CheckBox)findViewById(R.id.windows);
Button generate=(Button)findViewById(R.id.generate);
final TextView result=(TextView)findViewById(R.id.result);
android.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(((CheckBox)view).isChecked())
result.setText("Android Checked");
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
823 次 |
| 最近记录: |