首页 > 解决方案 > 使用 viewpager 制作图像视图

问题描述

我正在尝试在我的应用程序中创建一个滑动图像视图窗口,所以我使用 viewpager。但是 android studio 写了关于 java.lang.ClassCastException: androidx.viewpager.widget.ViewPager cannot be cast to android.widget.ImageView at this string:

ImageView imageView = view.findViewById(R.id.view_pager);

我知道这是另一种观点。但我不知道如何连接正确的 imageView。请帮忙。

MyPager 类:

  import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.viewpager.widget.PagerAdapter;

public class MyPager extends PagerAdapter {
    private Context context;
    public MyPager(Context context) {
        this.context = context;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = LayoutInflater.from(context).inflate(R.layout.authorization, null);
        ImageView imageView = view.findViewById(R.id.view_pager);
        imageView.setImageDrawable(context.getResources().getDrawable(getImageAt(position)));
        container.addView(view);
        return view;
    }

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

    @Override
    public int getCount() {
        return 7;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return object == view;
    }
    private int getImageAt(int position) {
        switch (position) {
            case 0:
                return R.drawable.logo0;
            case 1:
                return R.drawable.logo1;
            case 2:
                return R.drawable.logo2;
            case 3:
                return R.drawable.logo3;
            case 4:
                return R.drawable.logo4;
            case 5:
                return R.drawable.logo5;
            case 6:
                return R.drawable.logo6;
            default:
                return R.drawable.logo0;
        }
    }

}

标签: androidandroid-layoutandroid-viewpagerimageview

解决方案


在“instantiateItem”函数中编辑通胀行

View view = LayoutInflater.from(context).inflate(R.layout.authorization, null);

View view = LayoutInflater.from(context).inflate(R.layout.pager_item, null);

推荐阅读