android - 使用 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;
}
}
}
解决方案
在“instantiateItem”函数中编辑通胀行
View view = LayoutInflater.from(context).inflate(R.layout.authorization, null);
至
View view = LayoutInflater.from(context).inflate(R.layout.pager_item, null);
推荐阅读
- sql - sqlalchemy 按列中的唯一值分组
- spring - Spring Boot Kafka 消息传递。如何使用 SpEL 管理处理程序访问
- docker - 如何重新定义父母dockerfile的标签?
- sql - SQL 篮子分析分组查询
- angular - Angular:测试返回 observables 的守卫
- r - R Shiny 确保 pdf 缩放到 iframe 大小
- vue.js - 记录 rootState 和组件的挂载钩子中发生的所有突变?
- bluetooth - 选择频道的蓝牙模块服务模式(认证)
- chart.js - 反向报价单
- java - Java2D Disposer 线程使 JVM 崩溃