在Android中图片的自动切换不仅可以实现自动切换,而且还可以使用手动切换。而且一般在切换的时候,在图片下方还带有其他内容的切换,用来标记是第几个图片的切换。
实现效果如下:
具体的示例代码如下:
布局代码:
</ScrollView
dot_focus.xml文件代码如下:
dot_normal.xml文件代码如下:
Activity代码:
public class MainActivity extends AppCompatActivity {
private ArrayList imageViews= new ArrayList();
private ArrayListdots=new ArrayList();
private ViewPager vp;
private int image[]={R.drawable.denglu,R.drawable.disanye,R.drawable.hhh};
private int oldPosition=0;
private int currentItem;
private ScheduledExecutorService scheduledExecutorService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取图片资源
for (int i=0;i<image.length;i++){
ImageView imageView=new ImageView(this);
imageView.setImageResource(image[i]);
imageViews.add(imageView);
}
//显示的点的集合
dots.add(findViewById(R.id.p1));
dots.add(findViewById(R.id.p2));
dots.add(findViewById(R.id.p3));
vp=findViewById(R.id.viewContent);
vp.setAdapter(new ViewPagerAdapter());
vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
//点的效果切换
dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
dots.get(position).setBackgroundResource(R.drawable.dot_fouced);
oldPosition=position;
currentItem=position;
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
class ViewPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return imageViews.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view==object;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
View v=imageViews.get(position);
container.removeView(v);
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
View v=imageViews.get(position);
container.addView(v);
return v;
}
}
@Override
protected void onStart() {
super.onStart();
scheduledExecutorService= Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(),2,2, TimeUnit.SECONDS);
}
class ViewPagerTask implements Runnable{
@Override
public void run() {
currentItem=(currentItem+1)%image.length;
handler.obtainMessage().sendToTarget();
}
}
Handler handler=new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
vp.setCurrentItem(currentItem);
}
};
}
作者:爱的小爽