图像滑块在活动中有效,但在片段中无效

时间:2020-03-24 05:53:58

标签: android

这段视频https://www.youtube.com/watch?v=1AS5HcXPpqk中的代码在活动中效果很好,但是当我尝试以片段形式实现它时,它就会崩溃。

java代码和xml文件

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_facts, container, false);

    ImageSlider imageSlider = (ImageSlider) getView().findViewById(R.id.slide);
    List<SlideModel> slideModels = new ArrayList<>();
    slideModels.add(new SlideModel(R.drawable.ic_launcher_background, "Image1"));
    slideModels.add(new SlideModel(R.drawable.ic_launcher_background, "Image2"));
    slideModels.add(new SlideModel(R.drawable.ic_launcher_background, "Image3"));
    imageSlider.setImageList(slideModels, true);


    return view;
    }

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="#E4E3E3">


    <com.denzcoskun.imageslider.ImageSlider
    android:id="@+id/slide"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    app:auto_cycle="true"
    app:delay="0"
    app:period="1000"
    app:corner_radius="20"
    />

    </RelativeLayout>

2 个答案:

答案 0 :(得分:0)

更改此行

ImageSlider imageSlider = (ImageSlider) getView().findViewById(R.id.slide);

ImageSlider imageSlider = (ImageSlider) getActivity().findViewById(R.id.slide);

您需要传递正确的上下文getActivity()

答案 1 :(得分:0)

不要

ImageSlider imageSlider = (ImageSlider) getView().findViewById(R.id.slide);

要做

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

    View view = inflater.inflate(R.layout.fragment_facts, container, false);
    ImageSlider imageSlider = (ImageSlider) view.findViewById(R.id.slide);