我正在使用viewpager库来实现图像滑块,但不知道如何将其实现为自动滚动。这是我的代码。
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentPagerAdapter implements IconPagerAdapter{
private int[] Images = new int[] { R.drawable.viewpager, R.drawable.viewpager,
R.drawable.viewpager, R.drawable.viewpager,R.drawable.viewpager, R.drawable.viewpager
};
protected static final int[] ICONS = new int[] { R.drawable.logo,
R.drawable.logo, R.drawable.logo, R.drawable.logo,R.drawable.logo, R.drawable.logo };
private int mCount = Images.length;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return new SliderFragment(Images[position]);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mCount;
}
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
SliderFragment.java
public class SliderFragment extends SherlockFragment {
int imageResourceId;
public SliderFragment(int i) {
imageResourceId = i;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ImageView image = new ImageView(getActivity());
image.setImageResource(imageResourceId);
LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
layout.setGravity(Gravity.CENTER);
layout.addView(image);
return layout;
}
}
MainActivity.java
mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
vPager = (ViewPager) findViewById(R.id.pager);
pIndicator = (PageIndicator) findViewById(R.id.indicator);
vPager.setAdapter(mAdapter);
pIndicator.setViewPager(vPager);
((CirclePageIndicator) pIndicator).setSnap(true);
请指导我如何使用自动滚动实现它,以便图像在预定义的时间后自动滚动。
答案 0 :(得分:2)
page=0;
timer=new TimerTask() {
@Override
enter code here
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
viewPager.setCurrentItem(page % 4); // 4= no. of page in viewpager
page++;
}
});
}
};
Timer time=new Timer();
time.schedule(timer, 0, 3000); //3000 millisecond for replace the viewpager page
答案 1 :(得分:0)
我使用计时器线程解决了它。在特定时间后,我更改了视图寻呼机图像,该图像成为自动滚动。