在我的应用中,我需要一个图像滑块,我已经使用View pager做到了,但是我希望图像每2秒自动更改一次。我无法做到这一点。
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about, container,false);
viewPager = (ViewPager) rootView.findViewById(R.id.viewPager);
adapter = new CustomSwipeAdapter(this.getActivity());
viewPager.setAdapter(adapter);
indicator = (CircleIndicator) rootView.findViewById(R.id.indicator);
indicator.setViewPager(viewPager);
return rootView;
}
这是我的片段类。
public class CustomSwipeAdapter extends PagerAdapter {
private int[] image_resource = {R.drawable.sample_1, R.drawable.sample_2};
private Context ctx;
private LayoutInflater layoutInflater;
public CustomSwipeAdapter(Context ctx) {
this.ctx = ctx;
}
@Override
public int getCount() {
return image_resource.length;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return (view == object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.image_swipe_layout, container, false);
ImageView imageview = (ImageView) item_view.findViewById(R.id.image_view);
imageview.setImageResource(image_resource[position]);
container.addView(item_view);
return item_view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
}
这是我的适配器类。我希望该图像自动更改。请帮帮我。
答案 0 :(得分:0)
我很久以前编写的代码,它执行类似的操作,也许可以为您提供帮助。
final Handler handler = new Handler();
final Runnable update = () -> {
if (currentPage == list.size()) {
currentPage = 0;
}
pager.setCurrentItem(currentPage++, true);
};
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(update);
}
}, 2500, 2500);
@Override
protected void onDestroy() {
super.onDestroy();
timer.cancel();
}
因此,您设置了一个计时器,该计时器在一定的时间间隔(此处为〜2.5秒)后被调用,当计时器启动时,您将检查适配器的当前页面是否到达末尾,然后将其重置为0,否则将其递增