Recent projects need to implement them by figure show product images, when users click on the images need to zoom, according to user, of course, still can take more pictures slide switch, amplifier, reduce image operations, such as was more simple to implement, few words said, we are talking with code, code directly.

Implementation steps:

1. Display of effect drawings; 2. Add relevant dependencies to the project; 3. Click the wheel image to enter the picture enlargement and display page 5. Adapter 6 required for the picture enlargement and display page. 7. Solve the Bug in picture scaling

Implementation process: 1. The display of effect drawings

2. Add related dependencies to the project

    implementation 'com. Youth. The banner, the banner: 1.4.9'
    implementation 'com. Making. Bumptech. Glide: glide: 4.5.0'
    implementation 'com.com mit451: PhotoView: 1.
Copy the code

3. The main interface achieves the effect of the wheel broadcast graph

public class MainActivity extends AppCompatActivity implements OnBannerListener {

    private Banner banner;
    private ArrayList<String> list_path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
        initListener();
    }

    private void initView() {
        banner = findViewById(R.id.banner);
    }

    private void initData() {
        setBanner(); // Set the rotation chart} private voidinitListener() {} /** */ private voidsetBannerList_path = new ArrayList<>(); List_path.add ("https://sami-1256315447.picgz.myqcloud.com/article/201908/2a919def19fc47e3aa0d75d8c227ab1b.jpg");
        list_path.add("https://sami-1256315447.picgz.myqcloud.com/article/201908/d027d1efc0564c44bb979ba0bd21f560.jpg");
        list_path.add("https://sami-1256315447.picgz.myqcloud.com/article/201908/bbb930d66e5a48baa8d3c143544d7631.jpg");
        list_path.add("https://sami-1256315447.picgz.myqcloud.com/article/201908/fb1721b8c9be4da9949fcdd26fc902a2.jpg");
        list_path.add("https://sami-1256315447.picgz.myqcloud.com/article/201908/08b58dde9b284638b44e2d03c4cb9acf.jpg");
        list_path.add("https://sami-1256315447.picgz.myqcloud.com/article/201908/d3caeb6129ee43df87f5c1e1058d96fc.jpg");
        list_path.add("https://sami-1256315447.picgz.myqcloud.com/article/201908/9fd01c4add07473db31ba850f20a7232.jpg");
        list_path.add("http://a.hiphotos.baidu.com/image/pic/item/00e93901213fb80e3b0a611d3fd12f2eb8389424.jpg"); // Set the built-in styles. There are six methods you can click into to experience using one by one. banner.setBannerStyle(BannerConfig.NUM_INDICATOR); // Set the image loader to banner. SetImageLoader (new ImgLoader()); // set image url or address set banner. SetImages (list_path); / / set the animation effects of shuffling, containing a variety of special effects, can point into the method to find the one-by-one experience banner. SetBannerAnimation (Transformer. The Default). // Set the interval for banner.setdelayTime (3000); // Set whether to auto-cast, default is "yes" banner. IsAutoPlay (true); // Set the position of the indicator, little dots, left, middle and right. Banner. SetIndicatorGravity (BannerConfig. CENTER) / / the above content can be written as chain layout, this is by listening. More important. Here's how. .setonBannerListener (this) // The last method that must be called to start the multicast graph. .start(); @override public void OnBannerClick(int position) {Intent Intent = new Intent(this, imgactivity.class);  intent.putStringArrayListExtra("imgData", list_path);
        intent.putExtra("clickPosition", position); startActivity(intent); } private class ImgLoader extends ImageLoader {@override public void displayImage(Context Context, Object path, ImageView imageView) { Glide.with(context).load((String) path).into(imageView); }}}Copy the code

4. Click the rote image to enter the image enlargement display page

public class BigImgActivity extends AppCompatActivity {
    private ViewPagerFixed viewPager;
    private TextView tvNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_big_img);
        initView();
    }

    private void initView() { viewPager = findViewById(R.id.viewpager); tvNum = findViewById(R.id.tv_num); Final ArrayList<String> imgData = getIntent().getStringArrayListExtra("imgData");
        int clickPosition = getIntent().getIntExtra("clickPosition", 0); / / add the adapter PhotoPagerAdapter viewPagerAdapter = new PhotoPagerAdapter (getSupportFragmentManager (), imgData); viewPager.setAdapter(viewPagerAdapter); viewPager.setCurrentItem(clickPosition); / / set the selected image position viewPager. AddOnPageChangeListener (new viewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                tvNum.setText(String.valueOf(position + 1) + "/"+ imgData.size()); } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } }); }}Copy the code

5. The adapter required to enlarge the picture display page

Public class PhotoPagerAdapter extends FragmentPagerAdapter {private final ArrayList<String> urlList; public PhotoPagerAdapter(FragmentManager fm, ArrayList<String> urlList) { super(fm); this.urlList=urlList; } @Override public Fragment getItem(int position) {return PhotoFragment.newInstance(urlList.get(position));
    }

    @Override
    public int getCount() {
        returnurlList.size(); }}Copy the code

6. Obtain the URL of the fragment to display the image

public class PhotoFragment extends Fragment { private String url; private PhotoView mPhotoView; /** * Get the url that the fragment needs to display the image ** @param url * @return
     */
    public static PhotoFragment newInstance(String url) {
        PhotoFragment fragment = new PhotoFragment();
        Bundle args = new Bundle();
        args.putString("url", url);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        url = getArguments().getString("url");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_img, container, false); mPhotoView = view.findViewById(R.id.photoview); / / set the zoom type, default ScaleType. CENTER (can not) / / mPhotoView setScaleType (ImageView. ScaleType. CENTER); / / long press event mPhotoView. SetOnLongClickListener (new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                //Toast.makeText(getActivity(), "Long press event", Toast.LENGTH_SHORT).show();
                return true; }}); / / click event mPhotoView. SetOnPhotoTapListener (new PhotoViewAttacher.OnPhotoTapListener() {
            @Override
            public void onPhotoTap(View view, float x, float y) {
                //Toast.makeText(getActivity(), "Click the event to close the activity in the real project.", Toast.LENGTH_SHORT).show(); getActivity().finish(); }}); Green. With (getContext()).load(URL)//.placeholder(r.mpmap.ic_launcher)// Local image displayed when the image is not displayed during loading // .error(r.map.ic_launcher)// Image displayed when loading an exception //.centercrop ()// Image image fills the size set by the ImageView // .fitCenter()// The scaled image is measured equal to or less than the ImageView boundary range, and the image will be fully displayed.returnview; }}Copy the code

In the process of testing, when zooming in and out of the enlarged picture, we encountered the following Bug:

 java.lang.IllegalArgumentException: pointerIndex out of range
Copy the code

Problem solution:

Customize ViewPager to override onTouchEvent and onInterceptTouchEvent

public class ViewPagerFixed extends android.support.v4.view.ViewPager {
 
    public ViewPagerFixed(Context context) {
        super(context);
    }
 
    public ViewPagerFixed(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        try {
            return super.onTouchEvent(ev);
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        }
        return false;
    }
 
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        try {
            return super.onInterceptTouchEvent(ev);
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        }
        return false; }}Copy the code

Layout file:

<? 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"
    android:background="#fff">

    <com.showly.testimagedemo.view.ViewPagerFixed
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TextView
        android:id="@+id/tv_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textColor="#ffffff"
        android:textSize="30sp" />

</RelativeLayout>
Copy the code

The implementation is complete. Need Demo source code can be in the bottom of the public number reply: “TestImageDemo” can be obtained.


The following is our personal public account (LongXuanzhigu). Our articles published later will be synchronized to this account, which is convenient for exchanging and learning Android knowledge and sharing personal articles. If you have any questions, please leave a message: