onCreateView 寻呼机适配器

onCreateView pager adapter

尝试在空对象引用上调用虚拟方法'void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)'

我正在尝试使用 android material 设计实现滑动标签布局。但它给了我 NullPointerException。到目前为止,这是我的代码:

public class HomeFragment 扩展片段 {

private HomeViewModel homeViewModel;
private List<Slide> listSlides;
private ViewPager slidePager;
private TabLayout indicator;


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

    homeViewModel =
            ViewModelProviders.of(this).get(HomeViewModel.class);
    View root = inflater.inflate(R.layout.fragment_home, container, false);

     listSlides = new ArrayList<>();
     listSlides.add(new Slide(R.drawable.a, "slide title"));
     listSlides.add(new Slide(R.drawable.b, "slide title"));

     final SliderPagerAdapter adapter = new SliderPagerAdapter(getContext(), listSlides);

     homeViewModel.getText().observe(this, new Observer<String>() {
         @Override
         public void onChanged(@Nullable String s) {
             slidePager.setAdapter(adapter);
         }
     });



    return root;

}

}

public class SliderPagerAdapter 扩展了 PagerAdapter {

private Context mText;
private List<Slide> mList;

public SliderPagerAdapter(Context mText, List<Slide> mList) {
    this.mText = mText;
    this.mList = mList;
}


@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {


    LayoutInflater inflater = (LayoutInflater) mText.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View slideLayout = inflater.inflate(R.layout.slider_item,null);

    ImageView slideImg = slideLayout.findViewById(R.id.slide_img);
    TextView slideText= slideLayout.findViewById(R.id.slide_title);

    slideImg.setImageResource(mList.get(position).getImage());
    slideText.setText(mList.get(position).getTitle());

    container.addView(slideLayout);
    return slideLayout;


}

@Override
public int getCount() {
    return mList.size();
}

@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
    return view == object;
}

@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
    container.removeView((View) object);
}

}

您没有实例化 slidePager 所以当您尝试设置适配器时,它实际上是一个空对象。您应该在 ViewPager 上调用 findViewById