Java 使用片段下的android-findViewById NULL

Java 使用片段下的android-findViewById NULL,java,android,Java,Android,我英语说得不好。所以很多事情都很尴尬。另外,我希望我能理解,所以我使用了谷歌翻译 我有空指针错误的源代码 我怎样才能修好它 首先是Xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout

我英语说得不好。所以很多事情都很尴尬。另外,我希望我能理解,所以我使用了谷歌翻译

我有空指针错误的源代码

我怎样才能修好它

首先是Xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ToggleButton
            android:id="@+id/toggleButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.50"
            android:text="ToggleButton" />

        <ToggleButton
            android:id="@+id/toggleButton2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.50"
            android:text="ToggleButton" />
    </LinearLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/pager2"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />

</LinearLayout>

使用
onCreateView
中的
view
而不是
getView()
来初始化ViewPager:

    ViewPager mViewPager = (ViewPager)view.findViewById(R.id.pager2);

(ViewPager)getView()中使用
view
而不是
getView()
。findViewById(R.id.pager2)。在
onCreateView
中,
getView
为空,如果您想使用
getView()
您可以使用
onViewCreated()
方法+1轻松接受此答案。如果此答案对您有帮助
    ViewPager mViewPager = (ViewPager)view.findViewById(R.id.pager2);