1、添加依赖
implementation 'com.github.bumptech.glide:glide:4.6.1'
compile 'com.github.chrisbanes:PhotoView:2.0.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
2、实现fragmentactivity:
/*** 作者:created by meixi* 邮箱:13164716840@163.com* 日期:2018/9/21 14*/public class ImagePagerActivity extends FragmentActivity {private static final String TAG = "ImagePagerActivity";private static final String STATE_POSITION = "STATE_POSITION";public static final String EXTRA_IMAGE_INDEX = "image_index";public static final String EXTRA_IMAGE_URLARRAYS = "image_urlArrays";private HackyViewPager mPager;private int pagerPosition;private TextView indicator;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.image_xinshi_detail_pager);mPager = (HackyViewPager) findViewById(R.id.vp_pager);indicator = (TextView) findViewById(R.id.indicator);initVariables();initEvents();}private void initVariables() {pagerPosition = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0);ArrayList<String> urlArrays = getIntent().getStringArrayListExtra(EXTRA_IMAGE_URLARRAYS);ImagePagerAdapter mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), urlArrays);mPager.setAdapter(mAdapter);CharSequence text = getString(R.string.viewpager_indicator, 1, mPager.getAdapter().getCount());indicator.setText(text);}//这块的考虑再说@Overrideprotected void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);// outState.putInt(STATE_POSITION, mPager.getCurrentItem());}private void initEvents() {// 更新下标mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {@Overridepublic void onPageScrollStateChanged(int arg0) {}@Overridepublic void onPageScrolled(int arg0, float arg1, int arg2) {}@Overridepublic void onPageSelected(int arg0) {CharSequence text = getString(R.string.viewpager_indicator, arg0 + 1, mPager.getAdapter().getCount());indicator.setText(text);}});mPager.setCurrentItem(pagerPosition);}private class ImagePagerAdapter extends FragmentStatePagerAdapter {public ArrayList<String> urlArrays;public ImagePagerAdapter(FragmentManager fm, ArrayList<String> urlArrays) {super(fm);this.urlArrays = urlArrays;}@Overridepublic int getCount() {return urlArrays == null ? 0 : urlArrays.size();}@Overridepublic Fragment getItem(int position) {String url = urlArrays.get(position);return ImageDetailFragment.newInstance(url);}}
}
3、两个工具类:
public class ImageDetailFragment extends Fragment {private static final String TAG = "ImageDetailFragment";private String mImageUrl;private View rootView;private PhotoView mImageView;private ProgressBar progressBar;private TextView baocunte;private PhotoViewAttacher mAttacher;private String SAVE_PIC_PATH = Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)? Environment.getExternalStorageDirectory().getAbsolutePath() : "/mnt/sdcard";//private String SAVE_REAL_PATH = SAVE_PIC_PATH + "/good/savePic";//保存的确Bitmap bitmap;public static ImageDetailFragment newInstance(String imageUrl) {final ImageDetailFragment f = new ImageDetailFragment();final Bundle args = new Bundle();args.putString("url", imageUrl);f.setArguments(args);return f;}@Overridepublic void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);mImageUrl = getArguments() != null ? getArguments().getString("url") : null;new Thread(runnable).start();}@Nullable@Overridepublic View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {// return super.onCreateView(inflater, container, savedInstanceState);if (rootView == null) {rootView = inflater.inflate(R.layout.image_xinshi_detail_fragment, container, false);mImageView = (PhotoView) rootView.findViewById(R.id.image);progressBar = (ProgressBar) rootView.findViewById(R.id.loading);baocunte =(TextView)rootView.findViewById(R.id.baochunte);Log.e(TAG, "onCreateView:---------------- ");}else {ViewGroup parent = (ViewGroup) rootView.getParent();if (parent != null) {parent.removeView(rootView);}}return rootView;}/* 策略解说:all:缓存源资源和转换后的资源none:不作任何磁盘缓存source:缓存源资源result:缓存转换后的资源*/@Overridepublic void onActivityCreated(@Nullable Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);progressBar.setVisibility(View.VISIBLE);Glide.with(ImageDetailFragment.this).load(mImageUrl).placeholder(R.mipmap.icon_defaultimg) // 占位图.error(R.mipmap.icon_errorimg).diskCacheStrategy(DiskCacheStrategy.RESULT)//图片缓存模式.listener(new GlideRequestListener()).into(mImageView);}//glide 请求的回调private class GlideRequestListener implements RequestListener {@Overridepublic boolean onException(Exception e, Object model, Target target, boolean isFirstResource) {Toast.makeText(getActivity(), "加载图片失败", Toast.LENGTH_SHORT).show();progressBar.setVisibility(View.GONE);return false;}//这个用于监听图片是否加载完成@Overridepublic boolean onResourceReady(Object resource, Object model, Target target, boolean isFromMemoryCache, boolean isFirstResource) {mAttacher = new PhotoViewAttacher(mImageView);mAttacher.setOnPhotoTapListener(new OnPhotoTapListener() {@Overridepublic void onPhotoTap(ImageView view, float x, float y) {getActivity().finish();}});mAttacher.setOnLongClickListener(new View.OnLongClickListener() {@Overridepublic boolean onLongClick(View v) {Log.i("Lgq","...... "+mImageUrl);showNormalDialogOne();Toast.makeText(getActivity(), "触发长按事件", Toast.LENGTH_SHORT).show();return false;}});baocunte.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {try {saveFile(bitmap, System.currentTimeMillis() + ".jpg");} catch (IOException e) {e.printStackTrace();}}});progressBar.setVisibility(View.GONE);return false;}}private void saveFile(Bitmap bm, String fileName) throws IOException {String subForder = SAVE_REAL_PATH;File foder = new File(subForder);if (!foder.exists()) foder.mkdirs();File myCaptureFile = new File(subForder, fileName);Log.v("lgq","图片保持。。。。。。。。"+myCaptureFile);Log.v("lgq","图片保持。。。。。getPath。。。"+myCaptureFile.getPath());if (!myCaptureFile.exists()) myCaptureFile.createNewFile();BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);bos.flush();bos.close();Toast.makeText(getContext(),"已保存在/good/savePic目录下", Toast.LENGTH_SHORT).show();//发送广播通知系统Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);Uri uri = Uri.fromFile(myCaptureFile);intent.setData(uri);getActivity().sendBroadcast(intent);}@SuppressLint("HandlerLeak")private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {if (msg.what == 1) {}}};Runnable runnable = new Runnable() {@Overridepublic void run() {try {bitmap = ((BitmapDrawable) loadImageFromUrl(mImageUrl)).getBitmap();Message msg = new Message();msg.what = 1;handler.sendMessage(msg);} catch (IOException e) {e.printStackTrace();}}};private static Drawable loadImageFromUrl(String url) throws IOException {URL m = new URL(url);InputStream i = (InputStream) m.getContent();return Drawable.createFromStream(i, "src");}private void showNormalDialogOne() {/* @setIcon 设置对话框图标* @setTitle 设置对话框标题* @setMessage 设置对话框消息提示* setXXX方法返回Dialog对象,因此可以链式设置属性*/final AlertDialog.Builder normalDialog = new AlertDialog.Builder(getContext());normalDialog.setTitle("提示");normalDialog.setMessage("确定保存图片!");normalDialog.setPositiveButton("确定",new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {try {saveFile(bitmap, System.currentTimeMillis() + ".jpg");} catch (IOException e) {e.printStackTrace();}// delehistory();//dosomething}});normalDialog.setNegativeButton("取消",new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});normalDialog.show();}}
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
public class HackyViewPager extends ViewPager {private static final String TAG = "HackyViewPager";public HackyViewPager(Context context) {super(context);}public HackyViewPager(Context context, AttributeSet attrs) {super(context, attrs);}@Overridepublic boolean onInterceptTouchEvent(MotionEvent ev) {try {return super.onInterceptTouchEvent(ev);} catch (IllegalArgumentException e) {// 不理会Log.e(TAG, "hacky viewpager error1");return false;} catch (ArrayIndexOutOfBoundsException e) {// 不理会Log.e(TAG, "hacky viewpager error2");return false;}}@Overridepublic boolean onTouchEvent(MotionEvent ev) {try {return super.onTouchEvent(ev);} catch (IllegalArgumentException ex) {ex.printStackTrace();}return false;}}
/
附:
<string name="viewpager_indicator">%1$d/%2$d</string>
<color name="white">#FFffff</color>
icon_defaultimg.png。占位图
icon_errorimg.png、错误图
demo链接:https://download.csdn.net/download/meixi_android/10681365