报错: java.lang.UnsupportedOperationException: Required method instantiateItem was not overridden
出现场景: 在Android Studio中初次使用viewPager。
错误显示: 从主页面跳转至显示viewPager的页面时程序直接关闭。
原因判断: 自定义PagerAdapter中未重写instantiateItem方法
问题解决: 在PagerAdapter中重写了instantiateItem方法与destroyItem方法(这个不写也会报错)
原因分析: 自定义PagerAdapter由于是继承PagerAdapter,需要重写其定义的四个接口方法:
getCount()
instantiateItem()
isViewFromObject()
destroyItem()
要点牢记: 重写PagerAdapter类时一定要重写相应的四个方法。
整体代码: 修正前:
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import java.util.ArrayList;
public class MyPageViewAdapter extends PagerAdapter {
private ArrayList<View> viewLists;
public MyPageViewAdapter(ArrayList<View> viewLists) {
super();
this.viewLists = viewLists;
}
@Override
public int getCount() {
return viewLists.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
}
修正后:
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import java.util.ArrayList;
public class MyPageViewAdapter extends PagerAdapter {
private ArrayList<View> viewLists;
public MyPageViewAdapter(ArrayList<View> viewLists) {
super();
this.viewLists = viewLists;
}
@Override
public int getCount() {
return viewLists.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(viewLists.get(position));
}
public Object instantiateItem(ViewGroup container, int position) {
container.addView(viewLists.get(position));
return viewLists.get(position);
}
}
|