ViewPage实现轮播图
MainActivity类
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
//要加载的图片
private int[] imgIds = {
R.mipmap.pic1,
R.mipmap.pic2,
R.mipmap.pic3,
};
private ViewPager viewPager;
private Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
//获得当前的位置
int currentItem = viewPager.getCurrentItem();
//跳转到指定位置
viewPager.setCurrentItem(currentItem + 1);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.viewPager);
//设置适配器
viewPager.setAdapter(new MyAdapter(imgIds, this));
//定时器 每两秒执行一次
new Timer().schedule(new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(1);
}
}, 0, 2000);
}
}
MyAdapter类
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
public class MyAdapter extends PagerAdapter {
private int[] imagesResource;
private Context context;
public MyAdapter(int[] imagesResource, Context context) {
this.imagesResource = imagesResource;
this.context = context;
}
//获取ViewPager显示数据个数
@Override
public int getCount() {
if (imagesResource == null || imagesResource.length <= 0) {
return 0;
}
return Integer.MAX_VALUE;
}
//判断view和obj是否为同一个view
@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) {
container.removeView((View) object);
}
//实例化数据集合中的每一个数据
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
//获得布局
View view = LayoutInflater.from(context).inflate(R.layout.layout, null);
//获得数量
ImageView imageView = view.findViewById(R.id.imageView);
//设置资源
imageView.setImageResource(imagesResource[position % imagesResource.length]);
container.addView(view);
return view;
}
}
主布局
<?xml version="1.0" encoding="utf-8"?><androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="wrap_content"
android:layout_height="280dp"/>
ViewPage加载的布局
<?xml version="1.0" encoding="utf-8"?>