ViewPager和NullObjectReference错误

时间:2017-03-06 22:59:25

标签: android android-layout android-fragments android-viewpager android-adapter

我遇到了将适配器设置为ViewPager的问题。每次我得到一个NullObjectReference错误。我的代码出了什么问题?

1)布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

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

    <android.support.v4.view.PagerTabStrip
        android:id="@+id/pager_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:paddingBottom="4dp"
        android:paddingTop="4dp" />

</android.support.v4.view.ViewPager>
</LinearLayout>

2)Java类:

public class FoodFragment extends Fragment {

Toolbar toolbar;
ViewPager viewPager;
TabsPagerAdapter pagerAdapter;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

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

    setRetainInstance(true);

      ((AppCompatActivity)getActivity())
    .getSupportActionBar().setDisplayShowTitleEnabled(true);
    ((AppCompatActivity)getActivity())
    .getSupportActionBar().setTitle(R.string.food);
    toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
    toolbar.setBackgroundColor(Color.parseColor("#f6a632"));

    pagerAdapter = new    TabsPagerAdapter(getActivity()
   .getSupportFragmentManager());
    viewPager = (ViewPager) getActivity().findViewById(R.id.view_pager);
    viewPager.setAdapter(pagerAdapter);

    return inflater.inflate(R.layout.fragment_food, container, false);
}
}

调用viewPager.setAdapter(pagerAdapter)时,我总是遇到这个错误;线。

1 个答案:

答案 0 :(得分:0)

原因是你的onCreateView。在片段中,首先需要先为视图片段展开片段,然后从该视图中查找findViewById。 您可以在下面看到一个示例:

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

    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_food, container, false);

    // get your view by: rootView.findViewById()
    // for example:
    viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);

    // do others...

    return rootView;
}