PhotoView單擊退出、雙擊放大縮小、滑動(dòng)恢復(fù)上一頁(yè)狀態(tài)

添加依賴

//圖片預(yù)覽 photoView
api 'com.github.chrisbanes:PhotoView:2.1.3'

一、Activity

public class PhotoViewActivity extends AppCompatActivity {
    private ViewPager VP_photo;
    private PhotoPagerAdapter pagerAdapter;
    private LinearLayout ll_points;
    private int lastPosition;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setFullScreen(getWindow());//設(shè)置全屏模式
        setContentView(R.layout.activity_photoview);
        initUi();
        initData();
    }

    private void initUi() {
        String[] photoLists = getIntent().getStringArrayExtra("photoList");
        int photoPosition = getIntent().getIntExtra("photoPosition", 0);
        pagerAdapter = new PhotoPagerAdapter(this, photoLists);
        VP_photo = findViewById(R.id.VP_photo);
        ll_points = findViewById(R.id.ll_points);
        VP_photo.setAdapter(pagerAdapter);
        for (int i = 0; i < photoLists.length; i++) {
            //根據(jù)viewPager的數(shù)量,添加白點(diǎn)指示器
            ImageView view = new ImageView(this);
            view.setBackgroundResource(R.drawable.point_back);
            //給點(diǎn)設(shè)置寬高
            int px = getResources().getDimensionPixelOffset(R.dimen.x6);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(px, px);
            params.leftMargin = px;
            //給view設(shè)置參數(shù)
            view.setLayoutParams(params);
            //將圖片添加到線性布局中
            ll_points.addView(view);
        }
        lastPosition = photoPosition;
        ll_points.getChildAt(lastPosition).setBackgroundResource(R.drawable.point_white);
        VP_photo.setCurrentItem(photoPosition);
        VP_photo.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                position = position % photoLists.length;
                //獲取子頁(yè)面數(shù)量
                int childCount = VP_photo.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    //獲取當(dāng)前頁(yè)面的view
                    View child = VP_photo.getChildAt(i);
                    //獲取當(dāng)前頁(yè)面中的PhotoView
                    PhotoView photoView = child.findViewById(R.id.item_pv);
                    if (photoView != null) {
                        PhotoViewAttacher photoViewAttacher = photoView.getAttacher();
                        if (photoViewAttacher.getScale() != photoViewAttacher.getMinimumScale()) {//圖片縮放過(guò)恢復(fù)初始狀態(tài)
                            //第一個(gè)參數(shù)是獲取photoViewAttacher自帶的縮放大小最小值,第二個(gè)和第三個(gè)參數(shù)設(shè)置縮放中心
                            photoViewAttacher.setScale(photoViewAttacher.getMinimumScale(), 0f, 0f, true);
                        }
                    }
                }
                ll_points.getChildAt(lastPosition).setBackgroundResource(R.drawable.point_back);
                ll_points.getChildAt(position).setBackgroundResource(R.drawable.point_white);
                lastPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    private void initData() {
    }
}

二、Activity xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/rl"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <androidx.viewpager.widget.ViewPager
        android:id="@+id/VP_photo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/black" />

    <LinearLayout
        android:id="@+id/ll_points"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="@dimen/x20"
        android:gravity="center"
        android:orientation="horizontal" />

</RelativeLayout>

三、pagerAdapter

public class PhotoPagerAdapter extends PagerAdapter {
    private String[] imgList;
    private Activity context;
    public PhotoPagerAdapter(Activity context, String[] imgList) {
        this.imgList = imgList;
        this.context = context;
    }
    @Override
    public int getCount() {
        return imgList.length;
    }
    @Override
    public boolean isViewFromObject(@NotNull View view, @NotNull Object object) {
        //當(dāng)創(chuàng)建新的條目,又反回來(lái),判斷view是否可以被復(fù)用(即是否存在)
        return view == object;
    }
    @NotNull
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        //container  容器  相當(dāng)于用來(lái)存放imageView
        PhotoView photoView = (PhotoView) LayoutInflater.from(context).inflate(R.layout.activity_photoview_item, null);
        Glide.with(context).load(imgList[position]).placeholder(R.drawable.ic_launcher_background).into(photoView);
        //把圖片添加到container中
        photoView.setOnDoubleTapListener(new PhotoViewDoubleTapListener(context, photoView));
        container.addView(photoView);
        return photoView;
    }

    //銷毀條目
    @Override
    public void destroyItem(ViewGroup container, int position, @NotNull Object object) {
        //object:剛才創(chuàng)建的對(duì)象,即要銷毀的對(duì)象
        container.removeView((View) object);
    }
}

四、pagerAdapter xml

<?xml version="1.0" encoding="utf-8"?>
<com.github.chrisbanes.photoview.PhotoView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/item_pv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="fitCenter" />

五、因?yàn)榭蚣芾锩鏇]有實(shí)現(xiàn)單擊退出,并且兩次雙擊放大。修改為,雙擊一次放大再雙擊縮小。

package com.app.ccmvp.adapter;

import android.app.Activity;
import android.view.GestureDetector;
import android.view.MotionEvent;

import com.app.ccmvp.R;
import com.github.chrisbanes.photoview.PhotoView;

/**
 * 修改為點(diǎn)擊一次再雙擊就恢復(fù)原圖
 */
public class PhotoViewDoubleTapListener implements GestureDetector.OnDoubleTapListener {
    private Activity activity;
    private PhotoView photoView;

    public PhotoViewDoubleTapListener(Activity activity, PhotoView photoView) {
        this.activity = activity;
        this.photoView = photoView;

    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
       //重寫單擊方法,實(shí)現(xiàn)退出頁(yè)面
        activity.finish();
        activity.overridePendingTransition(R.anim.alpha_fade, R.anim.alpha_hide);//頁(yè)面跳轉(zhuǎn)跟退出時(shí)設(shè)置出場(chǎng)入場(chǎng)動(dòng)畫
        return false;
    }

    @Override
    public boolean onDoubleTap(MotionEvent me) {
        try {
            float scale = photoView.getScale();
            float x = me.getX();
            float y = me.getY();
            if (scale < photoView.getMediumScale()) {
                photoView.setScale(photoView.getMediumScale(), x, y, true);
            } else if (scale >= photoView.getMediumScale() && scale < photoView.getMaximumScale()) {
               //關(guān)鍵代碼,當(dāng)放大一次之后再點(diǎn)擊就縮小  
                photoView.setScale(photoView.getMinimumScale(), x, y, true);
            } else {
                photoView.setScale(photoView.getMinimumScale(), x, y, true);
            }
        } catch (ArrayIndexOutOfBoundsException e1) {
            // Can sometimes happen when getX() and getY() is called
        }

        return true;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {
        return false;
    }
}

過(guò)度動(dòng)畫相關(guān)代碼,我這邊是設(shè)置漸變動(dòng)畫,可以根據(jù)自己的需求修改。

alpha_fade
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_longAnimTime"
    android:fromAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="1.0" />
<?xml version="1.0" encoding="utf-8"?>

alpha_hide
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_longAnimTime"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="0.0" />

最后使用

 private String[] imglist = { 
"https://ss1.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=82f1640b19ce36d3bd0485300af23a24/fcfaaf51f3deb48f5510390ffc1f3a292cf578e2.jpg",    
"https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=ff6ed7cfa718972bbc3a06cad6cc7b9d/267f9e2f07082838304837cfb499a9014d08f1a0.jpg",
"https://ss2.baidu.com/vo3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=56577be956afa40f23c6c8dd9b66038c/562c11dfa9ec8a1346809b3bfb03918fa1ecc057.jpg",      
"https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=4a51c9cd7e8b4710d12ffbccf3ccc3b2/b64543a98226cffceee78e5eb5014a90f703ea09.jpg",
"https://ss3.baidu.com/9fo3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=a537b312164c510fb1c4e41a50582528/b8389b504fc2d562a746bd37eb1190ef77c66c99.jpg"
};
      //點(diǎn)擊單張圖片跳轉(zhuǎn)到圖片合集
        Intent intent = new Intent(getContext(), PhotoViewActivity.class);
        intent.putExtra("photoList", imglist);
        intent.putExtra("photoPosition", position);
        startActivity(intent);
        overridePendingTransition(R.anim.alpha_fade, R.anim.alpha_hide);

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容