TextView
单击按钮后,我想显示一个。
我的 Android 项目运行,但是当我单击按钮时,它会关闭我的应用程序。
显然我做错了什么。
这是我的代码:
public class AFragment extends Fragment {
Button button;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainView = (View) inflater.inflate(R.layout.afragment, container, false);
button = (Button) mainView.findViewById(R.id.button1);
addListenerOnButton();
return mainView;
}
public void addListenerOnButton() {
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View mainView) {
TextView view = (TextView) mainView.findViewById(R.id.textView1);
view.setText("Do whatever");
}
});
}
}
日志猫
02-14 21:51:35.896: E/AndroidRuntime(1536): FATAL EXCEPTION: main
02-14 21:51:35.896: E/AndroidRuntime(1536): java.lang.NullPointerException
02-14 21:51:35.896: E/AndroidRuntime(1536): at com.test.capitalpostouch.AFragment$1.onClick(AFragment.java:35)
02-14 21:51:35.896: E/AndroidRuntime(1536): at android.view.View.performClick(View.java:4084)
02-14 21:51:35.896: E/AndroidRuntime(1536): at android.view.View$PerformClick.run(View.java:16966)
02-14 21:51:35.896: E/AndroidRuntime(1536): at android.os.Handler.handleCallback(Handler.java:615)
02-14 21:51:35.896: E/AndroidRuntime(1536): at android.os.Handler.dispatchMessage(Handler.java:92)
02-14 21:51:35.896: E/AndroidRuntime(1536): at android.os.Looper.loop(Looper.java:137)
02-14 21:51:35.896: E/AndroidRuntime(1536): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-14 21:51:35.896: E/AndroidRuntime(1536): at java.lang.reflect.Method.invokeNative(Native Method)
02-14 21:51:35.896: E/AndroidRuntime(1536): at java.lang.reflect.Method.invoke(Method.java:511)
02-14 21:51:35.896: E/AndroidRuntime(1536): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-14 21:51:35.896: E/AndroidRuntime(1536): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-14 21:51:35.896: E/AndroidRuntime(1536): at dalvik.system.NativeStart.main(Native Method)