Android - 将图像从可绘制对象加载到 ViewPager



我有一个ViewPager包括三个页面。每个页面都有一个 ImageViews,稍后我将从可绘制对象集中加载图像。

这是我的代码:

在片段上:

@BindView(R.id.viewPager)    
ViewPager mViewPager;
...
private List<Integer> getIntroResourceIds() {
    List<Integer> introResourceIds = new ArrayList<>();
    introResourceIds.add(R.layout.layout_intro_step1);
    introResourceIds.add(R.layout.layout_intro_step2);
    introResourceIds.add(R.layout.layout_intro_step3);
    return introResourceIds;
}

在每个布局介绍中,我都有一个具有不同 id 的ImageView。如在layout_intro_step_1

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="10">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_weight="3">
        <ImageView
            android:id="@+id/quickpay_intro_step3_image"
            style="@style/IntroImage" />
    </FrameLayout>
</LinearLayout>

问题是,当用户单击下一页时,我无法为每个布局介绍设置图像视图。请帮助我这个问题。

创建自定义寻呼机适配器

class CustomPagerAdapter extends PagerAdapter {
 int[] mResources = {
        R.drawable.first,
        R.drawable.second,
        R.drawable.third,
        R.drawable.fourth,
        R.drawable.fifth,
        R.drawable.sixth
};

    Context mContext;
    LayoutInflater mLayoutInflater;
 
    public CustomPagerAdapter(Context context) {
        mContext = context;
        mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
 
    @Override
    public int getCount() {
        return mResources.length;
    }
 
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((LinearLayout) object);
    }
 
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View itemView = mLayoutInflater.inflate(R.layout.pager_item, container, false);
 
        ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
        imageView.setImageResource(mResources[position]);
 
        container.addView(itemView);
 
        return itemView;
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
    }
}

在活动设置视图中,寻呼机适配器

mCustomPagerAdapter = new CustomPagerAdapter(this);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCustomPagerAdapter);

最新更新