0

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

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

公共类 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;

}

}

公共类 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);
}

}

4

1 回答 1

0

您没有实例化,slidePager所以当您尝试 setAdapter 时,它实际上是一个空对象。你应该findViewByIdViewPager.

于 2019-12-07T23:32:22.777 回答