android图片查看器,实现图片加载进度监听,实现保存图片

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

最新版本demo:https://download.csdn.net/download/meixi_android/14946943

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/415140.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

iPhone X Web 设计

iPhone X Web 设计 原文地址&#xff1a;https://webkit.org/blog/7929/designing-websites-for-iphone-x/ 开箱即用(开发者无需进行任何设置)&#xff0c;在iPhone X中&#xff0c;Safari 就可以完美的在全面屏上显示你既有的网站。网页内容会自动插入到显示的安全区域以至于不…

[转载] 我的WafBypass之道(SQL注入篇)

我的WafBypass之道&#xff08;SQL注入篇&#xff09; Web安全 作者&#xff1a;先知技术社区 2016-11-23 7,566【本文转自安全脉搏战略合作伙伴先知技术社区 原帖地址 安全脉搏编辑huan9740整理发布】 0x00 前言 去年到现在就一直有人希望我出一篇关于waf绕过的文章&#xf…

Linux之Ubuntu下安装屏幕录像软件(SimpleScreenRecorder)【摘抄】

本博文全文属于摘抄自&#xff1a; (见文末处参考文献)(由于担心原博文丢失&#xff0c;以后查找不到&#xff0c;故此原文摘抄&#xff0c;以备日后多次查阅) 在日常工作中&#xff0c;有时需要对屏幕进行录像&#xff0c;以制作讲解文档等。下面介绍在Linux上安装屏幕录像软件…

docker 目录 挂载

docker容器启动的时候&#xff0c;如果要挂载宿主机的一个目录&#xff0c;可以用-v参数指定。 譬如我要启动一个centos容器&#xff0c;宿主机的/share目录挂载到容器的/share目录&#xff0c;可通过以下方式指定&#xff1a; docker run -it -v /share:/share centos /bin/…

工作177:表单重置项目处理

<template><!--新建账号对话框--><el-dialog title"新建账号" :visible.sync"dialogFormVisible" close"close"><el-form ref"form" :model"form" size"medium" :label-width"formLabe…

docker删除所有镜像和容器

需求&#xff1a;重新进行开发&#xff0c;需要清空目前的镜像和容器。 1、删除容器 1&#xff09;首先需要停止所有的容器 docker stop $(docker ps -a -q) 2&#xff09;删除所有的容器&#xff08;只删除单个时把后面的变量改为image id即可&#xff09; docker rm $(d…

Android 自定义字体,设置字体

效果图 实现代码&#xff1a; 1、先下载字体文件.ttf 下载链接&#xff1a;http://font.chinaz.com/maobiziti.html 2、main文件夹下创建fonts文件夹&#xff0c;.ttf文件复制到fonts文件夹下 3、读取ttf文件 List<Typeface> mTypefaceList new ArrayList(); priva…

docker 安装 centos

1、设置docker 镜像加速 三个源 名称路径网易https://hub-mirror.c.163.com/阿里云https://<你的ID>.mirror.aliyuncs.com七牛云加速器https://reg-mirror.qiniu.com "registry-mirrors":["https://hub-mirror.c.163.com/","https://reg-mirr…

工作177:时间戳转换

main.js // 将时间戳转日期格式的过滤器 Vue.filter(dateFormat, (dataStr) > {var time new Date(dataStr);function timeAdd0(str) {if (str < 10) {str 0 str;}return str}var y time.getFullYear();var m time.getMonth() 1;var d time.getDate();var h time…

二.java下使用RabbitMQ实现hello world

上一篇文章介绍了windows环境下的安装和配置rabbitMQ&#xff0c;具体戳这边&#xff0c;一.windows环境下rabbit的的安装和配置。 现在我们可以着手编写hello world程序了&#xff0c;一窥RabbitMQ的效用&#xff0c;从rabbitmq的官网的get start进入rabbitMQ文档学习区&#…

工作180:前端是业务需求理解

1做一个系统之前 要明确数据的一个处理流程 才能避免做返工操作

docker centos ssh

1、创建一个容器 docker run -d -p 18022:22 -p 18000:8000 --privileged -v /Users/caowei/share:/share --name yf c17f22223248 /usr/sbin/init 2、进入容器 docker exec -it 39550a9d4610 /bin/bash 3、安装openssh和openssh-server yum install -y passwd openssh op…

Android自定义view详解,使用实例,自定义属性,贝塞尔曲线

//只会触发执行onDraw方法&#xff0c;只会改变绘制里面的内容,条目的绘制 invalidate(); //只会触发执行onDraw方法&#xff0c;但是可以在子线程中刷新 postInvalidate(); //view的布局参数改变之后刷新&#xff0c;比如view的宽度和高度都修改了&#xff0c;只能通过reques…

前端学习(2679):安装mysql_front

mysql front安装与使用教程 2020-04-10 11:32 更新mysql front一种小巧的管理Mysql的应用工具&#xff0c;那么这个工具该如何安装和使用呢&#xff1f;一起来看看吧。 一&#xff0c;mysql前端下载&#xff1a; mysql front下载地址&#xff1a;点击下载 二&#xff0c;mysql前…

Android RecyclerView 向上偏移解决、添加自定义分割线,瀑布流,ScrollView嵌套RecyclerView滑动卡顿

向上偏移解决 android:focusableInTouchMode"true" android:focusable"true" android:fillViewport"true" 卡顿解决方法 recyclerViewwg.setHasFixedSize(true); recyclerViewwg.setNestedScrollingEnabled(false); 删除条目&#xff1a; l…

前端学习(2678):懂代码之表格BaseTable编辑操作

第一步:编辑操作 <template slot-scope"scope"><el-buttontype"text"icon"el-icon-edit"click"handleEdit(scope.$index, scope.row)">编辑</el-button></template> 第二步 进行编辑处理 // 编辑操作handle…

工作182:表格渲染

<el-table :data"tableData" style"width: 100%" border> <!-- <el-table-column label"id" prop"1" align"center"></el-table-column>--><!--渲染账号名称--><el-table-column l…

Android 集成支付宝支付,支付宝支付2.0

成功起调支付宝支付 下载支付sdk复制到libs文件夹下并add as library&#xff1a;https://docs.open.alipay.com/54/104509 1、首先申请支付宝 企业账户 链接&#xff1a;https://memberprod.alipay.com/account/reg/enterpriseIndex.htm 备注&#xff1a;企业账户是以邮箱申…