我有调用Fragment的MainActivity,片段调用类是:
public class Main extends Fragment{
//public Main(){}
Button btn;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.main, container, false);
try{
btn = (Button) rootView.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView tx = (TextView)rootView.findViewById(R.id.TextView04);
tx.setText("hello World");
}
});
}catch(Exception e){
}
// View rootView = inflater.inflate(R.layout.main, container, false);
return rootView;
}
}
我的问题是,我无法在此片段中执行某些活动。 为了找出如何在这个片段中执行一些活动,我添加了一个TextView和一个Button,它将TextView的文本更改为" Hello World"单击按钮时。现在我尝试运行应用程序,一切都很好,但点击按钮后我收到错误:"不幸的是,应用程序已停止。",我不知道为什么我会收到错误像这样,我是android开发的新手,所以请帮忙,请解释你添加的所有内容。
Here is the Log Cat Error:
02-09 20:33:30.765: E/AndroidRuntime(13596): FATAL EXCEPTION: main
02-09 20:33:30.765: E/AndroidRuntime(13596): java.lang.NullPointerException
02-09 20:33:30.765: E/AndroidRuntime(13596): at info.androidhive.slidingmenu.Main$1.onClick(Main.java:29)
02-09 20:33:30.765: E/AndroidRuntime(13596): at android.view.View.performClick(View.java:4212)
02-09 20:33:30.765: E/AndroidRuntime(13596): at android.view.View$PerformClick.run(View.java:17476)
02-09 20:33:30.765: E/AndroidRuntime(13596): at android.os.Handler.handleCallback(Handler.java:800)
02-09 20:33:30.765: E/AndroidRuntime(13596): at android.os.Handler.dispatchMessage(Handler.java:100)
02-09 20:33:30.765: E/AndroidRuntime(13596): at android.os.Looper.loop(Looper.java:194)
02-09 20:33:30.765: E/AndroidRuntime(13596): at android.app.ActivityThread.main(ActivityThread.java:5371)
02-09 20:33:30.765: E/AndroidRuntime(13596): at java.lang.reflect.Method.invokeNative(Native Method)
02-09 20:33:30.765: E/AndroidRuntime(13596): at java.lang.reflect.Method.invoke(Method.java:525)
02-09 20:33:30.765: E/AndroidRuntime(13596): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
02-09 20:33:30.765: E/AndroidRuntime(13596): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-09 20:33:30.765: E/AndroidRuntime(13596): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
首先,你的代码中的Nothings是错误的,你的代码所知道的是正确的,你只是忘了一点。根据log-cat错误,你的textView id有问题,所以将你的id更改为与main.xml不同的id,然后将其写入代码然后尝试运行它。一件事,尝试删除你的try catch异常,这是没用的。这是您的代码的结论。
public class Main extends Fragment{
Button btn;
TextView tx;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.main, container, false);
btn = (Button) rootView.findViewById(R.id.button1);
tx = (TextView)rootView.findViewById(R.id.newID); //Change your textView ID into different ID
btn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
tx.setText("hello World");
}
});
return rootView;
}
}