onCreateView 分页机适配器



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

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

公共类 HomeFragment 扩展 Fragment {

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);
}

}

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

相关内容

  • 没有找到相关文章

最新更新