Android 空指针异常,findVidewById

Android 空指针异常,findVidewById,android,Android,我尝试在onCreate func中调用findviewbyd,它总是返回NULL。通过引用其他帖子,我已经在setContentview之后调用了findViewById,但是问题仍然存在,您能帮忙吗 谢谢 JC 在我的fragment_main.xml中 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tool

我尝试在onCreate func中调用findviewbyd,它总是返回NULL。通过引用其他帖子,我已经在setContentview之后调用了findViewById,但是问题仍然存在,您能帮忙吗

谢谢

JC

在我的fragment_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.testapp2.MainActivity$PlaceholderFragment" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />
<TextView
    android:id="@+id/myText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
<Button
    android:id="@+id/myButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />


</LinearLayout>
尝试使用findviewbydr.id.myText;不是super.findviewbydr.id.myText


并确保您使用的布局正确,如果您使用的是R.layout.activity\u main,那么您的布局必须是activity\u main.xml

奇怪:调用super.findviewbyd是多余的,您应该直接调用findviewbyd 错误:您声明您的文件名为fragment_main.xml,但代码引用了activity_main.xml 问:你的R进口线是什么样子的?也许你指错人了 所有视图都属于fragment_main.xml,在这种情况下,您应该在fragment中初始化视图,而不是在活动中

您已设置ContentViewr.layout.activity_main,以便findViewById在当前视图层次结构中查找视图。由于activtiy_main.xml没有这些视图,因此初始化失败

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView text = (TextView) rootView.findViewById(R.id.myText);  
Button button = (Button) rootView.findViewById(R.id.myButton);

return rootView;
}

您正在使用activity_main.xml,但显示的是'fragment_main.xml'。你确定你所使用的是正确的吗?这没有什么区别。如果它的片段,,,这一个是,如果你使用的是活动。。。。如果是片段,请在onCreateView上调用它,并使用充气机的根视图。。所以它将变成:view.findviewbyd。。。;谢谢它工作得很好。但是,我可以知道onCreate和onCreateView之间的区别吗?
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView text = (TextView) rootView.findViewById(R.id.myText);  
Button button = (Button) rootView.findViewById(R.id.myButton);

return rootView;
}