I’m trying to use carousel in fragment.
I’m using the following library https://github.com/denzcoskun/ImageSlideshow for image slider. In Activity the image slider works, but in fragment it doesn’t work. And there was no particular error in Logcat and Log.
It also confirmed that both versions 0.0.6 and 0.1.0 can be done in activity and not in fragment. How can I use this slide in fragment?
In activity code (this is working)
ImageSlider imgSlider = findViewById(R.id.slider); List<SlideModel> slideModels = new ArrayList<>(); slideModels.add(new SlideModel(R.drawable.battery, ScaleTypes.FIT)); slideModels.add(new SlideModel("https://picsum.photos/200/300", ScaleTypes.FIT)); slideModels.add(new SlideModel("https://picsum.photos/id/237/200/300", ScaleTypes.FIT)); slideModels.add(new SlideModel("https://picsum.photos/seed/picsum/200/300", ScaleTypes.FIT)); imgSlider.setImageList(slideModels);
In fragment (it doesn’t work)
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentHomeBinding.inflate(inflater, container, false); View root = binding.getRoot(); //Carousel List<SlideModel> slideModels = new ArrayList<>(); slideModels.add(new SlideModel(R.drawable.battery, ScaleTypes.FIT)); slideModels.add(new SlideModel("https://picsum.photos/200/300", ScaleTypes.FIT)); slideModels.add(new SlideModel("https://picsum.photos/id/237/200/300", ScaleTypes.FIT)); slideModels.add(new SlideModel("https://picsum.photos/seed/picsum/200/300", ScaleTypes.FIT)); View view = inflater.inflate(R.layout.fragment_home, container, false); ImageSlider imageSlider = (ImageSlider) view.findViewById(R.id.layout_home_img_slide); imageSlider.setImageList(slideModels); return root; }
Advertisement
Answer
Use this code in your fragment.java file.
public class Home extends Fragment { ImageSlider imageSlider; public Home() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); imageSlider = (ImageSlider) view.findViewById(R.id.imageSlider); ArrayList<SlideModel> slideModels = new ArrayList<>(); // slideModels.add(new SlideModel(R.drawable.battery, ScaleTypes.FIT)); slideModels.add(new SlideModel("https://picsum.photos/200/300", ScaleTypes.FIT)); slideModels.add(new SlideModel("https://picsum.photos/id/237/200/300", ScaleTypes.FIT)); slideModels.add(new SlideModel("https://picsum.photos/seed/picsum/200/300", ScaleTypes.FIT)); // imageSlider.setImageList(slideModels); return view; } }