null オブジェクト参照で仮想メソッド「void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)」を呼び出そうとしています
Androidマテリアルデザインを使用してスライドタブレイアウトを実装しようとしています. しかし、それは私に NullPointerException を与えます。これまでの私のコードは次のとおりです。
public class HomeFragment extends 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;
}
}
public class SliderPagerAdapter extends 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);
}
}