我是Android新手,我以编程方式在Activity中包含一个片段。
这是我的片段类代码:
import com.pt.app.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MediaDisplayFragment extends Fragment {
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate (R.layout.media_display_fragment, container, false);
}
}
和我的活动代码:
public class ReadMediasView extends FragmentActivity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.read_medias_view);
Fragment fragment = new MediaDisplayFragment ();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace (R.id.readMediaViewContainerContent, fragment);
// Null Pointer Exception Here
TextView text = (TextView)fragment.getView ().findViewById (R.id.mediaDisplayText);
text.setVisibility (View.VISIBLE);
}
}
编辑:这是我的My Logcat输出:
FATAL EXCEPTION: main
Process: com.pt.app, PID: 28492
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pt.app/com.pt.app.ReadMediasView}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.pt.app.ReadMediasView.onCreate(ReadMediasView.java:91)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
... 11 more
为什么我会得到这个NullPointerException?谢谢。
答案 0 :(得分:0)
试试这个..
public class MediaDisplayFragment extends Fragment {
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate (R.layout.media_display_fragment, container, false);
TextView text = (TextView) view.findViewById (R.id.mediaDisplayText);
text.setVisibility (View.VISIBLE);
return view;
}
}