使用ViewPager在位图图像中滑动

时间:2018-12-03 10:16:23

标签: android bitmap android-viewpager swipe

我正在尝试创建一个可以在照片中滑动的应用程序。我目前将图像另存为位图。如何使用ViewPager滑动图像? (最好不要使用毕加索或Glide)

1 个答案:

答案 0 :(得分:0)

您说您有位图,将其存储在arraylist中。首先,为您的ViewPager制作一个适配器。

public class AdapterPagerImageSlider extends PagerAdapter {

    private ArrayList<Bitmap> bitmaps;
    private Context context;
    private LayoutInflater layoutInflater;

    public AdapterPagerImageSlider(Context context, ArrayList<Bitmap> bitmaps) {
        this.context = context;
        this.bitmaps= bitmaps;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.inflater_imageslider, container, false);

        ImageView imageView = view.findViewById(R.id.image);
        imageView.setImageBitmap(bitmaps.get(position)); //this set image from bitmap

        container.addView(view);
        return view;
    }

    @Override
    public int getCount() {
        return bitmaps.size();
    }

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

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

然后,进行布局并将其命名为inflater_imageslider

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

最后,声明该适配器并将其设置为您的ViewPager。

ArrayList<Bitmap> bitmaps = new ArrayList<>();
//code of storing your bitmaps to arraylist here : bitmaps.add(yourbitmap);
ViewPager vp = findViewById(R.id.vp);
AdapterPagerImageSlider adapter = new AdapterPagerImageSlider(MainActivity.this, bitmaps);
vp.setAdapter(adapter);

希望有帮助。