如何从PagerAdapter对象获取当前页面字段?

时间:2018-05-23 03:57:42

标签: android android-pageradapter

我正在开发一个使用ViewPagerPagerAdapter的应用。这工作正常,ViewPager显示正确的内容,但我需要在屏幕上移位当前图像的位图。我写了两个方法getBitmap()getId()。这是代码。

    public class CursorPagerAdaptor extends PagerAdapter {
    private Cursor mCursor;
    private Context mContext;
    private Bitmap bitmap;
    int id;
    LayoutInflater layoutInflater;
    public CursorPagerAdaptor(Context context,Cursor cursor){
        mContext = context;
        mCursor = cursor;
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        return mCursor.getCount();
    }

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

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View itemView= layoutInflater.inflate(R.layout.view_pager_items, container, false);
        final ImageView imageView = (ImageView) itemView.findViewById(R.id.image);
        final ProgressBar progressBar = (ProgressBar)itemView.findViewById(R.id.progress);
        //
        mCursor.moveToPosition(position);
        int urlIndex = mCursor.getColumnIndex(MetaDataInfo.COLUMN_PHOTOURL);
        String url = mCursor.getString(urlIndex);
        int idIndex = mCursor.getColumnIndex(MetaDataInfo._ID);
        id = mCursor.getInt(idIndex);

        container.addView(itemView);
        Glide.with(mContext)
                .asBitmap()
                .load(url).apply(new RequestOptions().dontAnimate().fitCenter())
                .into(new SimpleTarget<Bitmap>(640,480) {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        progressBar.setVisibility(View.GONE);
                        bitmap = resource;
                        imageView.setImageBitmap(resource);
                    }


                });
        ViewGroup parent = ((ViewGroup)itemView.getParent());
        if (parent!=null){ parent.removeView(itemView); }
        container.addView(itemView);
        return  itemView;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((RelativeLayout)object);
        bitmap = null;
    }
    public Bitmap getBitmap(){
     return bitmap;
    }
    public int getId(){
        return id;
    }
}

这工作正常但我需要Bitmap并且当前页面的ID可见。 当我调用mAdapter.getBitmap();时,此方法返回下一个屏幕外页面的位图。如何获取ViewPager的可见页面的位图?

1 个答案:

答案 0 :(得分:0)

ViewPager类有getCurrrentItem()方法。您可以使用getCurrentItem().

获取当前页面索引

使用类似:

viewPager.getCurrentItem()

您可以设置为:

viewPager.setCurrentItem(setCurrentItem);