Android中在fragment中自动轮播图片的主要代码
时间: 2024-02-05 13:13:03 浏览: 69
以下是一个在fragment中自动轮播图片的示例代码:
```java
public class BannerFragment extends Fragment {
private ViewPager mViewPager;
private List<Integer> mImageList;
private int mCurrentPage = 0;
private Timer mTimer;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_banner, container, false);
mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
mImageList = new ArrayList<>();
mImageList.add(R.drawable.image1);
mImageList.add(R.drawable.image2);
mImageList.add(R.drawable.image3);
mViewPager.setAdapter(new BannerPagerAdapter());
startAutoPlay();
return view;
}
private void startAutoPlay() {
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (mCurrentPage == mImageList.size()) {
mCurrentPage = 0;
}
mViewPager.setCurrentItem(mCurrentPage++, true);
}
});
}
}, 3000, 3000);
}
private class BannerPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return mImageList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(getActivity());
imageView.setImageResource(mImageList.get(position));
container.addView(imageView);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mTimer != null) {
mTimer.cancel();
}
}
}
```
这个示例代码中使用了ViewPager和一个Timer来实现自动轮播,每隔3秒钟就会自动切换到下一张图片。PagerAdapter的作用是为ViewPager提供数据源。在onCreateView方法中,我们创建了一个BannerPagerAdapter,然后将其设置给ViewPager。最后在onDestroy方法中,我们取消了Timer的计时任务,以免内存泄漏。
阅读全文