实现图片的左右滑动,可以通过ViewPager来实现。
主要分为以下几步:
1.activity的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager.widget.ViewPager
android:id="@+id/view_page"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
2.Activity代码
private void initView() {
viewPager = findViewById(R.id.view_page);
//设置适配器
viewPager.setAdapter(new PictureDetailAdapter(this, arrayList));
//Pager之间的间距
viewPager.setPageMargin(20);
//预加载
viewPager.setOffscreenPageLimit(3);
//默认第一张图 左右都有图
viewPager.setCurrentItem(currentIndex);
}
3.Adapter布局
里面就一个简单的ImageView
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ImageView>
4.Adapter代码
/**
* Description:
* <p>
* Time:2022/8/20-7:48
* Author:我叫PlusPlus
*/
public class PictureDetailAdapter extends PagerAdapter {
private Context mContext;
private ArrayList<String> dataList;
public PictureDetailAdapter(Context context, ArrayList<String> arrayList) {
mContext = context;
dataList = arrayList;
}
@Override
public Object instantiateItem(final ViewGroup container, final int position) {
//子View显示
View view = View.inflate(mContext, R.layout.item_picture_detail, null);
ImageView imageView = view.findViewById(R.id.image_view);
String data = dataList.get(position);
Bitmap bitmap = BitmapFactory.decodeFile(data);
imageView.setImageBitmap(bitmap);
//添加到父控件
container.addView(view);
return view;
}
@Override
public int getCount() {
return dataList == null ? 0 : dataList.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
//从viewpager中移除掉
container.removeView((View) object);
}
}