如何将适配器放入viewpager?

时间:2020-10-11 12:19:49

标签: android-studio android-fragments android-viewpager

这是MyPageAdapter的代码

public class MyPageAdapter extends PagerAdapter {
    int[] images = {R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4, R.drawable.img5, R.drawable.img6, R.drawable.img7, R.drawable.img8, R.drawable.img9, R.drawable.img10, R.drawable.img11, R.drawable.img12, R.drawable.img13
            , R.drawable.img14, R.drawable.img15, R.drawable.img16, R.drawable.img17, R.drawable.img18, R.drawable.img19, R.drawable.img20, R.drawable.img21, R.drawable.img22, R.drawable.img23, R.drawable.img24
            , R.drawable.img25, R.drawable.img26, R.drawable.img27, R.drawable.img28, R.drawable.img29, R.drawable.img30};

    private  LayoutInflater inflater;
    private Context context;

    public MyPageAdapter(Context context){
        this.context = context;
    }

    @Override
    public int getCount() {
        return images.length;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == ((LinearLayout)object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.fragment_slideshow, container, false);
        EditText editText = v.findViewById(R.id.editTextNumberDecimal);
        ImageView imageView = (ImageView)v.findViewById(R.id.imageView2);
        imageView.setImageResource(images[position]);
        int text = position+1;
        editText.setText(text);
        container.addView(v);
        return v;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.invalidate();
    }
}

这是SlideshowFragment的代码。

public class SlideshowFragment extends Fragment {


    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       View root = inflater.inflate(R.layout.fragment_slideshow, container, false);

       ViewPager2 viewPager2 = (ViewPager2) root.findViewById(R.id.pager);
       MyPageAdapter adapter = new MyPageAdapter(this);
       viewPager2.setAdapter(adapter);

        return root;
    }
}

我想在幻灯片片段中添加查看寻呼机,以便可以将30张照片作为幻灯片放映。 但是我不能在viewpager中使用setAdapter。 真的,除了制作和放置30张图片中每个图片的每个片段之外,还有别的方法吗? 请让我知道如何修改我的代码。

1 个答案:

答案 0 :(得分:0)

您正在混合使用Viewpager和Viewpager2,它们以两种完全不同的方式实现。

尝试


 ViewPager viewPager = (ViewPager) root.findViewById(R.id.pager);
       MyPageAdapter adapter = new MyPageAdapter(this);
       viewPager.setAdapter(adapter);

并将您的xml也更改为ViewPager小部件。

或者,您可以将适配器更改为RecyclerView.Adapter https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.Adapter

因为Viewpager2只是一个定制的RecyclerView。