0. 序言
- 本想节省时间在项目中使用轮播图框架,无奈找了一些都不是很满意。
- 我需要的只是一个普通效果的轮播图而已。
- 自己动手丰衣足食。
1. 效果图
2. 需求
3. 代码实现
- Activity:
public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {
//logt快捷键自动生成
private static final String TAG = "MainActivity";
//数据源
private int[] images = {R.drawable.ic_vp_02, R.drawable.ic_vp_03, R.drawable.ic_vp_05};
//存放ImageView对象的集合
private List mImageViewList = new ArrayList<>();
//标题
private int[] titles = {R.string.tv_02, R.string.tv_03, R.string.tv_05};
//轮播图的自动切换
private Handler mHandler = new Handler();
//判断是否在切换
private boolean isSwitch;
//轮播图
private MyViewPager mViewPager;
//指示器的容器
private LinearLayout mLayout;
//标题
private TextView mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化布局
initView();
//初始化图片
initImages();
//初始化vp
initViewPager();
//初始化点
initPoints();
//让轮播图初始化时显示第一张
mViewPager.setCurrentItem(1, false);
// 设置轮播图第一张的标题显示
mTitle.setText(titles[0]);
//传入MainActivity对象和数据给ViewPager
mViewPager.setActivity(this, titles);
//轮播图开启切换
startSwitch();
}
private void initView() {
mViewPager = (MyViewPager) findViewById(R.id.bt_main_vp);
mLayout = (LinearLayout) findViewById(R.id.ll_point_container);
mTitle = (TextView) findViewById(R.id.tv_title);
}
private void initViewPager() {
/**
* ① 让轮播图自适应大小指的是自适应高度
* ② 获取屏幕的宽,屏幕的宽就是viewpager的宽
* ③ 屏幕宽/vp应有的高度 = 图片的宽/图片的高
* ④ 有了宽和高,利用layoutParams动态设置vp的宽和高即可
*/
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int widthPixels = displayMetrics.widthPixels;
int height = widthPixels * 460 / 1226;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height);
mViewPager.setLayoutParams(params);
MyPagerAdapter myPagerAdapter = new MyPagerAdapter(mImageViewList);
mViewPager.setAdapter(myPagerAdapter);
mViewPager.addOnPageChangeListener(this);
}
/**
* 初始化轮播图的图片并自适应大小
*/
private void initImages() {
int size = images.length;
/**
* 要想实现无限轮播,在轮播图左右各添加一张图片,右边添加的是第一张图片,左边添加的是最后一张图片
* 给人的感觉是从最后一张轮播到了第一张,实际上是往右面添加了一张,左边同理
*/
for (int i = -1; i < size + 1; i++) {
ImageView imageView = new ImageView(this);
// 第一个ImageView显示数据源最后一张图片
if (i == -1) {
imageView.setImageResource(images[size - 1]);
} else if (i == size) {
//最后一个ImageView显示数据源第一张图片
imageView.setImageResource(images[0]);
} else {
imageView.setImageResource(images[i]);
}
mImageViewList.add(imageView);
}
}
/**
* 初始化点
*/
private void initPoints() {
//清空容器里面的布局
mLayout.removeAllViews();
for (int i = 0; i < images.length; i++) {
//小圆点
View view = new View(this);
//设置背景颜色
view.setBackgroundResource(R.drawable.point_gray_bg);
//小圆点布局参数
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(10, 10);
//右边距
layoutParams.rightMargin = 10;
//添加布局
mLayout.addView(view, layoutParams);
}
//让第一个点的背景为红色
mLayout.getChildAt(0).setBackgroundResource(R.drawable.point_red_bg);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
//动态设置标题内容
//修正标题下标:初始化
int pageIndex = 0;
//数据长度
int size = titles.length;
//加载第一张ImageView,实际标题是数据源最后一个
if (position == 0) {
pageIndex = size - 1;
//切换导致最后一个页面
mViewPager.setCurrentItem(size, false);
//position为最后一个ImageView,实际标题是数据源第一个
} else if (position == size + 1) {
pageIndex = 0;
//切换到第一个页面
mViewPager.setCurrentItem(1, false);
} else {
pageIndex = position - 1;
}
mTitle.setText(titles[pageIndex]);
//切换点
int childCount = mLayout.getChildCount();
for (int i = 0; i < childCount; i++) {
View view = mLayout.getChildAt(i);
//点根据标题走即可,因为数据的数量一致
if (pageIndex == i) {
//选中
view.setBackgroundResource(R.drawable.point_red_bg);
} else {
//未选中
view.setBackgroundResource(R.drawable.point_gray_bg);
}
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
/**
* 开始切换
*/
public void startSwitch() {
if (!isSwitch) {
mHandler.postDelayed(new SwitchTask(), 3000);
}
}
/**
* 停止切换
*/
public void stopSwitch() {
mHandler.removeCallbacksAndMessages(null);
isSwitch = false;
}
/**
* 切换的任务
*/
private class SwitchTask implements Runnable {
@Override
public void run() {
//切换逻辑
int currentItem = mViewPager.getCurrentItem();
if (currentItem == mImageViewList.size() - 1) {
currentItem = 0;
} else {
currentItem++;
}
mViewPager.setCurrentItem(currentItem);
mHandler.postDelayed(this, 3000);
}
}
/**
* 防止资源泄漏
*/
@Override
protected void onPause() {
super.onPause();
stopSwitch();
}
}
- PagerAdapter:
/**
* Created by FuKaiqiang on 2018-05-01.
* 轮播图的适配器
*/
public class MyPagerAdapter extends PagerAdapter {
private List mImageViewList;
public MyPagerAdapter(List imageViewList) {
mImageViewList = imageViewList;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = mImageViewList.get(position);
container.addView(view);
return view;
}
@Override
public int getCount() {
return mImageViewList != null ? mImageViewList.size() : 0;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
- 自定义ViewPager:
/**
* Created by FuKaiqiang on 2018-05-02.
*/
public class MyViewPager extends ViewPager {
private MainActivity mActivity;
private int mStartX;
private int mStartY;
private int[] titles;
public MyViewPager(Context context) {
super(context);
}
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setActivity(MainActivity mainActivity, int[] titles) {
mActivity = mainActivity;
this.titles = titles;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mStartX = (int) ev.getX();
mStartY = (int) ev.getY();
//停止轮播图的切换
mActivity.stopSwitch();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
int upX = (int) ev.getX();
int upY = (int) ev.getY();
if (mStartX == upX && mStartY == upY) {
int currentItem = getCurrentItem();
Toast.makeText(mActivity, titles[currentItem-1], Toast.LENGTH_SHORT).show();
}
//恢复轮播图的切换
mActivity.startSwitch();
break;
}
return super.dispatchTouchEvent(ev);
}
}
- layout:
- shape:
4. 下载地址:
链接:https://pan.baidu.com/s/1pUuCHN8TJXa_E2x9LX87eA 密码:0yku
5. 后续
如果大家喜欢这篇文章,欢迎点赞;如果想看更多前端移动端后端Java或Python方面的技术,欢迎关注!