android listview嵌套progreesbar更新进度 ftp
效果:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 图片上传不了?
本文能实现的功能 :listview嵌套progressbar实现进度显示上传,上传完毕后移除,继续上传未上传完成的,以及全选单选,listview子控件的回调监听等)
直接看适配器的代码:(主要用于的ftp的文件上传 两个list分别是名字与绝对路径)
Child2Adapter.java
package com.leng.fileupdate_new.Adapter; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.leng.fileupdate_new.Bean.FileUpdateStatus; import com.leng.fileupdate_new.R; import com.leng.fileupdate_new.contrl.CallBacklistview; import com.leng.fileupdate_new.contrl.FileManger; import com.leng.fileupdate_new.greendao.gen.DaoUtils; import com.leng.fileupdate_new.upload.uploadUtil.HProgressBar; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static com.leng.fileupdate_new.utils.Constanxs.updingMap; /** * Created by Administrator on 2017/9/27. */ public class Child2Adapter extends BaseAdapter implements View.OnClickListener { private LayoutInflater inflater; private Bitmap directory, file; int pvaluas; //存储文件名称 private ArrayList<String> names = null; //存储文件路径 private ArrayList<String> paths = null; private ArrayList<FileUpdateStatus> dates = null; private Context mContext; // 用来控制CheckBox的选中状况 private static HashMap<Integer, Boolean> isSelectedchild2; private List<View> viewList; private CallBacklistview mCallBack; //参数初始化 public Child2Adapter(Context context, ArrayList<String> na, ArrayList<String> pa,CallBacklistview callBack) { names = na; paths = pa; viewList = new ArrayList<>(); mContext = context; mCallBack=callBack; directory = BitmapFactory.decodeResource(context.getResources(), R.mipmap.wenjianjia); inflater = LayoutInflater.from(context); isSelectedchild2 = new HashMap<Integer, Boolean>(); initDate(); } // 初始化isSelected的数据 private void initDate() { for (int i = 0; i < paths.size(); i++) { getIsSelectedChild2().put(i, false); // Toast.makeText(mContext, "SDFSD", Toast.LENGTH_SHORT).show(); } } @Override public int getCount() { // TODO Auto-generated method stub return names.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return names.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder; if (null == convertView) { convertView = inflater.inflate(R.layout.child2_item, null); holder = new ViewHolder(); holder.text = (TextView) convertView.findViewById(R.id.icon_text); holder.image = (ImageView) convertView.findViewById(R.id.icon_image); holder.cb = (CheckBox) convertView.findViewById(R.id.dir_list_Check); holder.progressBar = (HProgressBar) convertView.findViewById(R.id.hpr); holder.pbutton = (Button) convertView.findViewById(R.id.pause_button); holder.sbutton = (Button) convertView.findViewById(R.id.start_button); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.pbutton.setOnClickListener(this); holder.pbutton.setTag(position ); holder.sbutton.setOnClickListener(this); holder.sbutton.setTag(position ); File f = new File(paths.get(position)); if (names.get(position).equals("@1")) { holder.text.setText("/返回跟目录"); holder.image.setImageBitmap(directory); } else if (names.get(position).equals("@2")) { holder.text.setText(".返回上级目录"); holder.image.setImageBitmap(directory); } else { holder.text.setText(f.getName()); if (f.isDirectory()) { holder.image.setImageBitmap(directory); } else if (f.isFile()) { if (FileManger.getSingleton().map.containsKey(getExtension(f))) { String famt = getExtension(f); if (famt != null) { if (famt.equals("jpg") || famt.equals("png") || famt.equals("bmp") || famt.equals("jpeg") || famt.equals("gif")) { Glide.with(mContext) .load(f.getAbsoluteFile()) .placeholder(R.drawable.ic_zhanweitu) .error(R.drawable.ic_tupian_shibai) // .diskCacheStrategy(DiskCacheStrategy.NONE) // .override(50, 50) .into(holder.image); // mapFamt.put(f.getAbsolutePath(), "/Images/"); // mapType.put(f.getAbsolutePath(), "1"); } else if (famt.equals("3gp") || famt.equals("mp4") || famt.equals("rmvb") || famt.equals("mpeg") || famt.equals("mpg") || famt.equals("asf") || famt.equals("avi") || famt.equals("wmv")) { Glide.with(mContext) .load(f.getAbsoluteFile()) .placeholder(R.drawable.ic_video_weijiazai_svg) .error(R.drawable.ic_video_svg) // .diskCacheStrategy(DiskCacheStrategy.NONE) // .override(50, 50) .into(holder.image); // mapFamt.put(f.getAbsolutePath(), "/Videos/"); // mapType.put(f.getAbsolutePath(), "3"); } else if (famt.equals("amr") || famt.equals("mp3") || famt.equals("m4a") || famt.equals("aac") || famt.equals("ogg") || famt.equals("wav") || famt.equals("mkv") || famt.equals("flac")) { Glide.with(mContext) .load(f.getAbsoluteFile()) .placeholder(R.drawable.ic_music_weijiazai_svg) .error(R.drawable.ic_music_svg) // .diskCacheStrategy(DiskCacheStrategy.NONE) // .override(50, 50) .into(holder.image); // mapFamt.put(f.getAbsolutePath(), "/Audios/"); // mapType.put(f.getAbsolutePath(), "2"); } holder.cb.setChecked(getIsSelectedChild2().get(position)); holder.progressBar.setProgress(DaoUtils.FileUserDaoQueryPrgresswhere(names.get(position))); Log.i("QWEQWE", getIsSelectedChild2().get(position) + ""); // int as = Integer.parseInt(updingMap.get(paths.get(position))+0)+holder.progressBar.getProgress(); // if(dates.get(position).isDownload()) { // holder.progressBar.setVisibility(View.VISIBLE); // holder.progressBar.setProgress(dates.get(position).getProgress()); // }else { // holder.progressBar.setVisibility(View.INVISIBLE); // } } else { Toast.makeText(mContext, "famt GESHI KONG", Toast.LENGTH_SHORT).show(); } } else { Glide.with(mContext) .load(R.drawable.ic_weishibie).error(R.drawable.ic_weishibie2).override(50, 50).into(holder.image); } } else { System.out.println(f.getName()); } } return convertView; } @Override public void onClick(View v) { mCallBack.click(v); } private class ViewHolder { private TextView text; private ImageView image; private CheckBox cb; private Button pbutton; private Button sbutton; private HProgressBar progressBar; } private Bitmap small(Bitmap map, float num) { Matrix matrix = new Matrix(); matrix.postScale(num, num); return Bitmap.createBitmap(map, 0, 0, map.getWidth(), map.getHeight(), matrix, true); } private static String getExtension(final File file) { String suffix = ""; String name = file.getName(); final int idx = name.lastIndexOf("."); if (idx > 0) { suffix = name.substring(idx + 1); } return suffix; } public static HashMap<Integer, Boolean> getIsSelectedChild2() { // isSelected.clear(); return isSelectedchild2; } public static void setIsSelectedChild2(HashMap<Integer, Boolean> isSelected) { isSelectedchild2 = isSelected; } public static void updataView(int posi, ListView listView, int values) { int visibleFirstPosi = listView.getFirstVisiblePosition(); int visibleLastPosi = listView.getLastVisiblePosition(); if (posi >= visibleFirstPosi && posi <= visibleLastPosi) { View view = listView.getChildAt(posi - visibleFirstPosi); ViewHolder holder = (ViewHolder) view.getTag(); holder.progressBar.setProgress(values); Log.i("ASDASD", "走岂不是很尴尬"); } } }
接口:CallBacklistview.java
package com.leng.fileupdate_new.contrl;import android.view.View;/*** Created by liuguodong on 2017/10/6.*/public interface CallBacklistview {void click(View view);}
子布局:child2_item.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"android:descendantFocusability="blocksDescendants"><RelativeLayoutandroid:id="@+id/dirRl"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="@drawable/fileexplorer_item_bg"android:gravity="center_vertical"android:padding="@dimen/view_10dp"><CheckBoxandroid:id="@+id/dir_list_Check"style="@style/CustomCheckBoxTheme"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_centerVertical="true"android:clickable="false"android:focusable="false" /><ImageViewandroid:id="@+id/icon_image"android:layout_width="35dp"android:layout_height="35dp"android:layout_centerVertical="true"android:layout_marginLeft="@dimen/view_10dp"android:layout_toRightOf="@+id/dir_list_Check"android:src="@drawable/bxfile_file_dir" /><TextViewandroid:id="@+id/icon_text"android:layout_width="wrap_content"android:layout_height="20dp"android:layout_marginLeft="@dimen/view_10dp"android:layout_toRightOf="@id/icon_image"android:gravity="start"android:textColor="@color/black"android:textSize="@dimen/text_12sp" /><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_below="@+id/icon_text"android:layout_marginLeft="10dp"android:layout_marginRight="50dp"android:layout_marginTop="5dp"android:layout_toRightOf="@+id/icon_image"><com.leng.fileupdate_new.upload.uploadUtil.HProgressBarandroid:id="@+id/hpr"android:layout_width="match_parent"android:layout_height="wrap_content"android:padding="5dp"android:progress="1"app:progress_text_color="#ff2903FC"app:progress_unreached_color="#ffBCB4E8" /></RelativeLayout><LinearLayoutandroid:layout_width="50dp"android:layout_height="50dp"android:layout_alignParentRight="true"android:layout_weight="1"android:focusable="false"android:clickable="true"android:orientation="vertical"><Buttonandroid:id="@+id/pause_button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="right|center_vertical"android:focusable="false"android:clickable="true"android:text="@string/pause"android:textSize="12sp" /><Buttonandroid:id="@+id/start_button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="right|center_vertical"android:focusable="false"android:clickable="true"android:text="@string/start"android:textSize="12sp"android:visibility="gone" /></LinearLayout></RelativeLayout></RelativeLayout>
FileManger.java
package com.leng.fileupdate_new.contrl;import android.content.Context;import android.util.Log;import com.leng.fileupdate_new.R;import com.leng.fileupdate_new.utils.MimeType;import java.io.File;import java.util.HashMap;import java.util.Map;/*** Created by Administrator on 2017/9/22.*/public class FileManger {private static final String TAG = "FileManger";public final Map<String, MimeType> map;public final Map<MimeType, Integer> resMap;private Context mContext;private volatile static FileManger fm = null;private FileManger() {map = new HashMap<String, MimeType>();map.put("amr", MimeType.MUSIC);map.put("mp3", MimeType.MUSIC);map.put("m4a", MimeType.MUSIC);map.put("aac", MimeType.MUSIC);map.put("ogg", MimeType.MUSIC);map.put("wav", MimeType.MUSIC);map.put("mkv", MimeType.MUSIC);map.put("flac", MimeType.MUSIC);map.put("3gp", MimeType.VIDEO);map.put("mp4", MimeType.VIDEO);map.put("rmvb", MimeType.VIDEO);map.put("mpeg", MimeType.VIDEO);map.put("mpg", MimeType.VIDEO);map.put("asf", MimeType.VIDEO);map.put("avi", MimeType.VIDEO);map.put("wmv", MimeType.VIDEO);// map.put("apk", MimeType.APK);map.put("bmp", MimeType.IMAGE);map.put("gif", MimeType.IMAGE);map.put("jpeg", MimeType.IMAGE);map.put("jpg", MimeType.IMAGE);map.put("png", MimeType.IMAGE);// map.put("doc", MimeType.DOC);// map.put("docx", MimeType.DOC);// map.put("rtf", MimeType.DOC);// map.put("wps", MimeType.DOC);// map.put("xls", MimeType.XLS);// map.put("xlsx", MimeType.XLS);// map.put("gtar", MimeType.RAR);// map.put("gz", MimeType.RAR);// map.put("zip", MimeType.RAR);// map.put("tar", MimeType.RAR);// map.put("rar", MimeType.RAR);// map.put("jar", MimeType.RAR);// map.put("htm", MimeType.HTML);// map.put("html", MimeType.HTML);// map.put("xhtml", MimeType.HTML);// map.put("java", MimeType.TXT);// map.put("txt", MimeType.TXT);// map.put("xml", MimeType.TXT);// map.put("log", MimeType.TXT);// map.put("pdf", MimeType.PDF);// map.put("ppt", MimeType.PPT);// map.put("pptx", MimeType.PPT);resMap = new HashMap<MimeType, Integer>();resMap.put(MimeType.APK, R.drawable.bxfile_file_apk);resMap.put(MimeType.DOC, R.drawable.bxfile_file_doc);resMap.put(MimeType.HTML, R.drawable.bxfile_file_html);resMap.put(MimeType.IMAGE, R.drawable.bxfile_file_unknow);resMap.put(MimeType.MUSIC, R.drawable.bxfile_file_mp3);resMap.put(MimeType.VIDEO, R.drawable.bxfile_file_video);resMap.put(MimeType.PDF, R.drawable.bxfile_file_pdf);resMap.put(MimeType.PPT, R.drawable.bxfile_file_ppt);resMap.put(MimeType.RAR, R.drawable.bxfile_file_zip);resMap.put(MimeType.TXT, R.drawable.bxfile_file_txt);resMap.put(MimeType.XLS, R.drawable.bxfile_file_xls);resMap.put(MimeType.UNKNOWN, R.drawable.bxfile_file_unknow);}public static FileManger getSingleton() {//先检查实例是否存在,如果不存在进入下面代码块if (fm == null) {//同步块,线程安全的创建实例synchronized (FileManger.class) {fm = new FileManger();}}return fm;}public int getFileNun(String path) {int arr=0;int a = 1;if (path.length() > 0) {File file = new File(path);File[] filearr = file.listFiles();if (filearr!=null&&filearr.length > 0) {for (int i = 0; i < filearr.length; i++) {String filetype = getExtension(filearr[i]);if (map.containsKey(filetype)) { //获取当前文件下所有音视频文件arr = a++;Log.i(TAG, filetype + arr);}}} else {arr=0;// Toast.makeText(mContext, "该目录下没有文件", Toast.LENGTH_SHORT).show();}} else {// Toast.makeText(mContext, "路径不正确", Toast.LENGTH_SHORT).show();}return arr;}private static String getExtension(final File file) {String suffix = "";String name = file.getName();final int idx = name.lastIndexOf(".");if (idx > 0) {suffix = name.substring(idx + 1);}return suffix;}}
HProgressBar.java
package com.leng.fileupdate_new.upload.uploadUtil;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Canvas;import android.graphics.Paint;import android.util.AttributeSet;import android.util.TypedValue;import android.widget.ProgressBar;import com.leng.fileupdate_new.R;public class HProgressBar extends ProgressBar {private static final int DEFAULT_TEXT_SIZE = 10;private static final int DEFAULT_TEXT_COLOR = 0XFFFC00D1;private static final int DEFAULT_COLOR_UNREACHED_COLOR = 0xFFd3d6da;private static final int DEFAULT_HEIGHT_REACHED_PROGRESS_BAR = 2;private static final int DEFAULT_HEIGHT_UNREACHED_PROGRESS_BAR = 2;private static final int DEFAULT_SIZE_TEXT_OFFSET = 10;/*** painter of all drawing things*/protected Paint mPaint = new Paint();/*** color of progress number*/protected int mTextColor = DEFAULT_TEXT_COLOR;/*** size of text (sp)*/protected int mTextSize = sp2px(DEFAULT_TEXT_SIZE);/*** offset of draw progress*/protected int mTextOffset = dp2px(DEFAULT_SIZE_TEXT_OFFSET);/*** height of reached progress bar*/protected int mReachedProgressBarHeight = dp2px(DEFAULT_HEIGHT_REACHED_PROGRESS_BAR);/*** color of reached bar*/protected int mReachedBarColor = DEFAULT_TEXT_COLOR;/*** color of unreached bar*/protected int mUnReachedBarColor = DEFAULT_COLOR_UNREACHED_COLOR;/*** height of unreached progress bar*/protected int mUnReachedProgressBarHeight = dp2px(DEFAULT_HEIGHT_UNREACHED_PROGRESS_BAR);/*** view width except padding*/protected int mRealWidth;protected boolean mIfDrawText = true;protected static final int VISIBLE = 0;public HProgressBar(Context context, AttributeSet attrs) {this(context, attrs, 0);}public HProgressBar(Context context, AttributeSet attrs,int defStyle) {super(context, attrs, defStyle);obtainStyledAttributes(attrs);mPaint.setTextSize(mTextSize);mPaint.setColor(mTextColor);}@Overrideprotected synchronized void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {int width = MeasureSpec.getSize(widthMeasureSpec);int height = measureHeight(heightMeasureSpec);setMeasuredDimension(width, height);mRealWidth = getMeasuredWidth() - getPaddingRight() - getPaddingLeft();}private int measureHeight(int measureSpec) {int result = 0;int specMode = MeasureSpec.getMode(measureSpec);int specSize = MeasureSpec.getSize(measureSpec);if (specMode == MeasureSpec.EXACTLY) {result = specSize;} else {float textHeight = (mPaint.descent() - mPaint.ascent());result = (int) (getPaddingTop() + getPaddingBottom() + Math.max(Math.max(mReachedProgressBarHeight,mUnReachedProgressBarHeight), Math.abs(textHeight)));if (specMode == MeasureSpec.AT_MOST) {result = Math.min(result, specSize);}}return result;}/*** get the styled attributes** @param attrs*/private void obtainStyledAttributes(AttributeSet attrs) {// init values from custom attributesfinal TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.HProgressBar);mTextColor = attributes.getColor(R.styleable.HProgressBar_progress_text_color,DEFAULT_TEXT_COLOR);mTextSize = (int) attributes.getDimension(R.styleable.HProgressBar_progress_text_size,mTextSize);mReachedBarColor = attributes.getColor(R.styleable.HProgressBar_progress_reached_color,mTextColor);mUnReachedBarColor = attributes.getColor(R.styleable.HProgressBar_progress_unreached_color,DEFAULT_COLOR_UNREACHED_COLOR);mReachedProgressBarHeight = (int) attributes.getDimension(R.styleable.HProgressBar_progress_reached_bar_height,mReachedProgressBarHeight);mUnReachedProgressBarHeight = (int) attributes.getDimension(R.styleable.HProgressBar_progress_unreached_bar_height,mUnReachedProgressBarHeight);mTextOffset = (int) attributes.getDimension(R.styleable.HProgressBar_progress_text_offset,mTextOffset);int textVisible = attributes.getInt(R.styleable.HProgressBar_progress_text_visibility,VISIBLE);if (textVisible != VISIBLE) {mIfDrawText = false;}attributes.recycle();}@Overrideprotected synchronized void onDraw(Canvas canvas) {canvas.save();canvas.translate(getPaddingLeft(), getHeight() / 2);boolean noNeedBg = false;float radio = getProgress() * 1.0f / getMax();float progressPosX = (int) (mRealWidth * radio);String text = getProgress() + "%";// mPaint.getTextBounds(text, 0, text.length(), mTextBound);float textWidth = mPaint.measureText(text);float textHeight = (mPaint.descent() + mPaint.ascent()) / 2;if (progressPosX + textWidth > mRealWidth) {progressPosX = mRealWidth - textWidth;noNeedBg = true;}// draw reached barfloat endX = progressPosX - mTextOffset / 2;if (endX > 0) {mPaint.setColor(mReachedBarColor);mPaint.setStrokeWidth(mReachedProgressBarHeight);canvas.drawLine(0, 0, endX, 0, mPaint);}// draw progress bar// measure text boundif (mIfDrawText) {mPaint.setColor(mTextColor);canvas.drawText(text, progressPosX, -textHeight, mPaint);}// draw unreached barif (!noNeedBg) {float start = progressPosX + mTextOffset / 2 + textWidth;mPaint.setColor(mUnReachedBarColor);mPaint.setStrokeWidth(mUnReachedProgressBarHeight);canvas.drawLine(start, 0, mRealWidth, 0, mPaint);}canvas.restore();}/*** dp 2 px** @param dpVal*/protected int dp2px(int dpVal) {return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dpVal, getResources().getDisplayMetrics());}/*** sp 2 px** @param spVal* @return*/protected int sp2px(int spVal) {return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,spVal, getResources().getDisplayMetrics());}}HProgressBar.java中的资源文件
<declare-styleable name="HProgressBar"><attr name="progress_unreached_color" format="color" /><attr name="progress_reached_color" format="color" /><attr name="progress_reached_bar_height" format="dimension" /><attr name="progress_unreached_bar_height" format="dimension" /><attr name="progress_text_size" format="dimension" /><attr name="progress_text_color" format="color" /><attr name="progress_text_offset" format="dimension" /><attr name="progress_text_visibility" format="enum"><enum name="visible" value="0" /><enum name="invisible" value="1" /></attr></declare-styleable>
使用:fragment使用的BlankFragmentChild2.java
private HashMap<String, Integer> mapIndex = new HashMap<>();private Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what) {case 9876:// showFile();break;case 4579:showFile();break;case 4560:if (isUplodFirstone) {showFile();isUplodFirstone = false;Log.i(TAG, "只允许走一遍");}else {Log.i(TAG, "是不是得从这只允许走一遍");}Bundle bundle = msg.getData();String pathname = bundle.getString("pathname");//这里接受到的信息可以开个线程模拟进度String progress = bundle.getString("progress");String path = bundle.getString("pathpath");int progressv = Integer.parseInt(progress);//upload发送过来的值// String uploadfilename = spitContDBfilename(pathname);//正在上传中的文件的名字FileUser2 ff = new FileUser2();//自定义实体类ff.setId(FileUtils.longPressLong(pathname));ff.setMFileProgresdao(progressv);ff.setMFileNamedao(pathname);ff.setMFilePathdao(path);APP.getDaoInstant().getFileUser2Dao().update(ff);//更新数据库 使用greendao存储数据int prgressValue = FileUserDaoQueryPrgresswhere(pathname);//根据id取出当前进度值if (mapIndex!=null&&mapIndex.size() > 0) {//mapIndex存放当前添加的listview列表名字与下标int dexwen = mapIndex.get(pathname);//取出当前这个名字的所在listview中对相应的下标Child2Adapter.updataView(dexwen, mChild2Listview, prgressValue);//更新值Log.i(TAG, " 按 " + "正在更新的小标是:" + dexwen + "值是 :" + prgressValue);if (prgressValue == 100) {//如果值大于100移除列表//获取是否打开上传完成后删除源文件boolean isDel = (boolean) SharedPreferencesUtils.getParam(mContext, "checkbox8", false);String activefileName = mListname.get(dexwen);Log.i(TAG, " 谁 :" + activefileName + " 移除列表");mHandler.sendEmptyMessage(4579);}Log.i(TAG, "mapIndex不为空 " + "要更新的下标是 :" + dexwen + " 更新的值是 :" + prgressValue + " map的大小是:" + mapIndex.size());} else {Log.i(TAG, "mapIndex ==null");}Log.i(TAG, pathname + "==" + progress + "int值 :" + progressv + "名字是 :" + spitContDBfilename(pathname) + "读取到的值是" + prgressValue);break;}}};
整个的BlankFragmentChild2.java代码
package com.leng.fileupdate_new.moudle;import android.app.Activity;import android.app.Dialog;import android.content.Context;import android.graphics.drawable.Drawable;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v4.app.Fragment;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.Button;import android.widget.ListView;import android.widget.RelativeLayout;import android.widget.Toast;import com.leng.fileupdate_new.APP;import com.leng.fileupdate_new.Adapter.Child2Adapter;import com.leng.fileupdate_new.Bean.FileUser;import com.leng.fileupdate_new.Bean.FileUser2;import com.leng.fileupdate_new.Bean.FileUserRevocation;import com.leng.fileupdate_new.MainActivity;import com.leng.fileupdate_new.R;import com.leng.fileupdate_new.contrl.CabackInfoNums;import com.leng.fileupdate_new.contrl.CallBacklistview;import com.leng.fileupdate_new.greendao.gen.DaoUtils;import com.leng.fileupdate_new.upload.TestBean;import com.leng.fileupdate_new.upload.UploadFileManager;import com.leng.fileupdate_new.utils.Constanxs;import com.leng.fileupdate_new.utils.FileUtils;import com.leng.fileupdate_new.utils.SharedPreferencesUtils;import com.leng.fileupdate_new.utils.SpUtil;import com.leng.other.CommomDialog2;import java.io.File;import java.util.ArrayList;import java.util.HashMap;import static com.leng.fileupdate_new.greendao.gen.DaoUtils.FileUserDaoQueryPrgresswhere;import static com.leng.fileupdate_new.moudle.BlankFragmentChild1.uploadFileManager;import static com.leng.fileupdate_new.utils.Constanxs.isUplodFirstone;public class BlankFragmentChild2 extends Fragment implements View.OnClickListener, CallBacklistview {private View view;private ListView mChild2Listview;private ArrayList<String> mListname = new ArrayList<>();private ArrayList<String> mListpath = new ArrayList<>();private MainActivity ma;private Context mContext;private boolean isSelectdAll = true;private Child2Adapter mAdapter;private int checktrueNums = 0;private RelativeLayout mChild2RelativeList;private RelativeLayout mChild2RelativeEmpty;private static final String TAG = "BlankFragmentChild2";private boolean isbtnchick = true;/*** 全选*/private Button mSelectAllUpding;/*** 撤销*/private Button mUpdateButtonUpding;/*** 删除*/private Button mDeletButtonUpding;int checkNum = 0;//初始化回调接口private CabackInfoNums cabackInfoNums;private HashMap<String, Integer> mapIndex = new HashMap<>();private Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what) {case 9876:// showFile();break;case 4579:showFile();break;case 4560:if (isUplodFirstone) {showFile();isUplodFirstone = false;Log.i(TAG, "只允许走一遍");}else {Log.i(TAG, "是不是得从这只允许走一遍");}Bundle bundle = msg.getData();String pathname = bundle.getString("pathname");String progress = bundle.getString("progress");String path = bundle.getString("pathpath");int progressv = Integer.parseInt(progress);//upload发送过来的值// String uploadfilename = spitContDBfilename(pathname);//正在上传中的文件的名字FileUser2 ff = new FileUser2();ff.setId(FileUtils.longPressLong(pathname));ff.setMFileProgresdao(progressv);ff.setMFileNamedao(pathname);ff.setMFilePathdao(path);APP.getDaoInstant().getFileUser2Dao().update(ff);//更新数据库int prgressValue = FileUserDaoQueryPrgresswhere(pathname);if (mapIndex!=null&&mapIndex.size() > 0) {int dexwen = mapIndex.get(pathname);Child2Adapter.updataView(dexwen, mChild2Listview, prgressValue);Log.i(TAG, " 按 " + "正在更新的小标是:" + dexwen + "值是 :" + prgressValue);if (prgressValue == 100) {//获取是否打开上传完成后删除源文件boolean isDel = (boolean) SharedPreferencesUtils.getParam(mContext, "checkbox8", false);String activefileName = mListname.get(dexwen);Log.i(TAG, " 谁 :" + activefileName + " 移除列表");FileUser fileUser = new FileUser();fileUser.setId(FileUtils.longPressLong(activefileName));fileUser.setMFileTypedao("7");APP.getDaoInstant().getFileUserDao().update(fileUser);mHandler.sendEmptyMessage(4579);if (isDel) {Log.i(TAG, "开启上传完成后删除源文件");FileUtils.delete(path);}}Log.i(TAG, "mapIndex不为空 " + "要更新的下标是 :" + dexwen + " 更新的值是 :" + prgressValue + " map的大小是:" + mapIndex.size());} else {Log.i(TAG, "mapIndex ==null");}Log.i(TAG, pathname + "==" + progress + "int值 :" + progressv + "名字是 :" + spitContDBfilename(pathname) + "读取到的值是" + prgressValue);break;}}};@Overridepublic void onAttach(Activity activity) {super.onAttach(activity);ma = (MainActivity) activity;ma.setmHandlerUpding(mHandler);cabackInfoNums = ma;}//线程管理对象@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {mContext = getActivity();view = inflater.inflate(R.layout.fragment_blank_fragment_child2, container, false);initView(view);return view;}private void initView(View view) {mChild2Listview = (ListView) view.findViewById(R.id.child2_listview);mChild2Listview.setOnItemClickListener(clickListener);mChild2RelativeList = (RelativeLayout) view.findViewById(R.id.child2Relative_list);mChild2RelativeEmpty = (RelativeLayout) view.findViewById(R.id.child2Relative_empty);mSelectAllUpding = (Button) view.findViewById(R.id.select_all_upding);mSelectAllUpding.setOnClickListener(this);mUpdateButtonUpding = (Button) view.findViewById(R.id.update_button_upding);mUpdateButtonUpding.setOnClickListener(this);mDeletButtonUpding = (Button) view.findViewById(R.id.delet_button_upding);mDeletButtonUpding.setOnClickListener(this);showFile();}/*** 去数据库作比对*/private boolean isDaoFileExits(String filename) {if (mListname.size() > 0) {for (int i = 0; i < DaoUtils.FileUserDaoQuerywhere("6").size(); i++) {if (DaoUtils.FileUserDaoQuerywhere("6").get(i).getId().equals(FileUtils.longPressLong(filename))) {return true;}}}return false;}/*** 截取远程服务端的名字*/private String spitContDBfilename(String name) {String[] ass = name.split("&");return ass[ass.length - 1];}@Overridepublic void onHiddenChanged(boolean hidden) {super.onHiddenChanged(hidden);if (!hidden) {showFile();} else {}}private int ifIndexWhen(String name) {if (mListname.size() > 0) {for (int i = 0; i < mListname.size(); i++) {if (mListname.get(i).equals(name)) {return i;}}}return 11111;}private void showFile() {mListname.clear();mListpath.clear();checkNum = 0;checktrueNums = 0;isSelectdAll = true;//标记删除后不能在全选if (DaoUtils.FileUserDaoQuerywhere("6") != null && DaoUtils.FileUserDaoQuerywhere("6").size() > 0) {mapIndex.clear();for (int i1 = 0; i1 < DaoUtils.FileUserDaoQuerywhere("6").size(); i1++) {String name = DaoUtils.FileUserDaoQuerywhere("6").get(i1).getMFileNamedao();String path = DaoUtils.FileUserDaoQuerywhere("6").get(i1).getMFilePathdao();mListname.add(name);mListpath.add(path);mapIndex.put(name, mapIndex.size());mChild2RelativeEmpty.setVisibility(View.GONE);mChild2RelativeList.setVisibility(View.VISIBLE);mAdapter = new Child2Adapter(mContext, mListname, mListpath, this);mChild2Listview.setAdapter(mAdapter);//保存正在上传的数量SharedPreferencesUtils.setParam(mContext, Constanxs.FOTERNUMSTWO, mListname.size() + "");Log.i(TAG, "查询到的数据是 :" + DaoUtils.FileUserDaoQuerywhere("6").get(i1).getMFileNamedao() + " map的size是: " + mapIndex.size());}} else {Log.i(TAG, "没有查询到数据");mChild2RelativeEmpty.setVisibility(View.VISIBLE);mChild2RelativeList.setVisibility(View.GONE);}setBtnSelectAllYes();//回调发送消息// cabackInfoNums.setInfoNums();}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.select_all_upding:if (mListname.size() > 0) {if (isSelectdAll) {selectAllfile(true);isSelectdAll = false;setBtnSelectAllNo();checktrueNums++;} else {selectAllfile(false);isSelectdAll = true;setBtnSelectAllYes();checktrueNums--;}} else {Toast.makeText(mContext, "当前文件下没有文件", Toast.LENGTH_SHORT).show();}break;case R.id.update_button_upding:if (uploadFileManager == null) {uploadFileManager = new UploadFileManager(mContext);}revocationFile(checkNum);break;case R.id.delet_button_upding:delfile(checkNum);break;}}private void showDialog() {new CommomDialog2(mContext, R.style.dialog, "请选择目标文件", new CommomDialog2.OnCloseListener() {@Overridepublic void onClick(Dialog dialog, boolean confirm) {dialog.dismiss();}}).show();}private void showDialogDelFile() {new CommomDialog2(mContext, R.style.dialog, "确认删除文件", new CommomDialog2.OnCloseListener() {@Overridepublic void onClick(Dialog dialog, boolean confirm) {if (confirm) {for (int i = 0; i < Child2Adapter.getIsSelectedChild2().size(); i++) {if (Child2Adapter.getIsSelectedChild2().get(i)) {String name = mListname.get(i);Log.i(TAG, "删除的文件是 :" + mListpath.get(i));TestBean tt = SpUtil.getObject(mContext, name);if (tt != null && tt.getUpLoadStatus().equals("1")) {//如果撤销的文件正在上传中 就暂停 并且删除远程服务端tt.setUpLoadStatus("2");SpUtil.putObject(mContext, name, tt);//再一次序列化uploadFileManager.pause(tt);}FileUtils.delete(mListpath.get(i));DaoUtils.FilUserDaoDel(name);}}mHandler.sendEmptyMessage(4579);}dialog.dismiss();}}).show();}private void showDialogRmeFile() {new CommomDialog2(mContext, R.style.dialog, "确认撤销文件", new CommomDialog2.OnCloseListener() {@Overridepublic void onClick(Dialog dialog, boolean confirm) {if (confirm) {for (int i = 0; i < Child2Adapter.getIsSelectedChild2().size(); i++) {if (Child2Adapter.getIsSelectedChild2().get(i)) {Log.i(TAG, "撤销的文件是 :" + mListpath.get(i) + " 撤销的文件类型是: " + DaoUtils.FileUserDaoQuerypathAderesswhere(mListname.get(i)));//获取要撤销的文件来自哪个目录String revocationType = DaoUtils.FileUserDaoQuerypathAderesswhere(mListname.get(i));String name = mListname.get(i);String path = mListpath.get(i);FileUser fileUser = new FileUser();fileUser.setId(FileUtils.longPressLong(name));fileUser.setMFileTypedao(revocationType);fileUser.setMFileProgresdao(0);fileUser.setMFileNamedao(name);fileUser.setMFilePathdao(path);APP.getDaoInstant().getFileUserDao().update(fileUser);updateRevocation(name, revocationType);//撤销后删除撤销匹配得文件// DaoUtils.FilUserRevocationDaoDel(name);//撤销后停止上传//?????TestBean tt = SpUtil.getObject(mContext, name);if (tt != null && tt.getUpLoadStatus().equals("1")) {//如果撤销的文件正在上传中 就暂停 并且删除远程服务端tt.setUpLoadStatus("2");SpUtil.putObject(mContext, name, tt);//再一次序列化uploadFileManager.pause(tt);}}}mHandler.sendEmptyMessage(4579);}dialog.dismiss();}}).show();}private void updateRevocation(String name, String type) {FileUserRevocation revocation = new FileUserRevocation();revocation.setId(FileUtils.longPressLong(name));revocation.setMFileTypedao(type);APP.getDaoInstant().getFileUserRevocationDao().insertOrReplace(revocation);}/*** 撤销*/private void revocationFile(int num) {if (num != 0) {showDialogRmeFile();} else {showDialog();}}private void delfile(int num) {if (num != 0) {showDialogDelFile();} else {showDialog();}}/*** v* 把全选按钮设置成为初始状态*/public void setBtnSelectAllYes() {mSelectAllUpding.setText(R.string.select_all); // 点击全选Button然后文字变成Drawable top = mSelectAllUpding.getResources().getDrawable(R.drawable.select_all);mSelectAllUpding.setCompoundDrawablesWithIntrinsicBounds(null, top,null, null);}/*** v* 把全选按钮设置成为初始状态*/public void setBtnSelectAllNo() {mSelectAllUpding.setText(R.string.desselect_all); // 点击全选Button然后文字变成Drawable top = mSelectAllUpding.getResources().getDrawable(R.drawable.desselect_all);mSelectAllUpding.setCompoundDrawablesWithIntrinsicBounds(null, top,null, null);}AdapterView.OnItemClickListener clickListener = new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> adapterView, final View view, int i, long l) {boolean checkIS = true;chcnlSels(i);if (checkNum == mListname.size()) {setBtnSelectAllNo();isSelectdAll = false;} else {setBtnSelectAllYes();isSelectdAll = true;}Toast.makeText(mContext, "==" + checkNum, Toast.LENGTH_SHORT).show();}};private static String getExtension(final File file) {String suffix = "";String name = file.getName();final int idx = name.lastIndexOf(".");if (idx > 0) {suffix = name.substring(idx + 1);}return suffix;}private void dataChanged() {mAdapter.notifyDataSetChanged();}private void chcnlSels(int a) {if (Child2Adapter.getIsSelectedChild2().get(a)) {Child2Adapter.getIsSelectedChild2().put(a, false);checkNum--;checktrueNums--;Toast.makeText(mContext, "取消" + a, Toast.LENGTH_SHORT).show();} else {Child2Adapter.getIsSelectedChild2().put(a, true);checkNum++;checktrueNums++;Toast.makeText(mContext, "选中" + a, Toast.LENGTH_SHORT).show();}dataChanged();}private void selectAllfile(boolean is) {// 遍历list的长度,将MyAdapter中的map值全部设为truefor (int i = 0; i < mListname.size(); i++) {Child2Adapter.getIsSelectedChild2().put(i, is);}if (is) {// 数量设为list的长度checkNum = mListname.size();} else {checkNum = 0;}// 刷新listview和TextView的显示dataChanged();}@Overridepublic void click(View view) {int postion = (int) view.getTag();Button pbutton = (Button) view.findViewById(R.id.pause_button);Button sbutton = (Button) view.findViewById(R.id.start_button);if (uploadFileManager == null) {uploadFileManager = new UploadFileManager(mContext);}String name = mListname.get(postion);TestBean tt = SpUtil.getObject(mContext, name);if (tt != null) {Log.i(TAG, "序列化本地数据" + "点击了继续上传 :格式" + tt.getCrateFileType() + " type :" + tt.getCrateFileTypenums() + "名字是:" + tt.getLocfileName() + "远程路径名字是 :" + tt.getRemotefilepath() + "是佛上传标识 :" + tt.getUpLoadStatus());String statusx = tt.getUpLoadStatus();if (statusx.equals("1")) {//暂停tt.setUpLoadStatus("2");SpUtil.putObject(mContext, name, tt);//再一次序列化pbutton.setText("开始");uploadFileManager.pause(tt);} else if (statusx.equals("2")) {tt.setUpLoadStatus("1");SpUtil.putObject(mContext, name, tt);//再一次序列化pbutton.setText("暂停");uploadFileManager.startUpLoad(tt);} else {Toast.makeText(mContext, "系统文件被删除", Toast.LENGTH_SHORT).show();}} else {Toast.makeText(mContext, "获取本地序列化对象失败", Toast.LENGTH_SHORT).show();}//// if (isbtnchick) {//暂停////// pbutton.setText("开始");//// isbtnchick = false;//// TestBean tt = fileStatusBeanMap.get(name);//// tt.setUpLoadStatus("2");//// uploadFileManager.pause(tt);////// } else {////// TestBean tt = fileStatusBeanMap.get(name);//// tt.setUpLoadStatus("1");//// uploadFileManager.startUpLoad(tt);//// Log.i(TAG, "" + "点击了继续上传 :格式" + tt.getCrateFileType() + " type :" + tt.getCrateFileTypenums() + "名字是:" + tt.getLocfileName() + "远程路径名字是 :" + tt.getRemotefilepath() + "是佛上传标识 :" + tt.getUpLoadStatus());// pbutton.setText("暂停");// isbtnchick = true;// }}@Overridepublic void onDestroy() {super.onDestroy();Log.i(TAG,"onDestroy");}@Overridepublic void onDestroyView() {super.onDestroyView();Log.i(TAG,"onDestroyView");}@Overridepublic void onDetach() {super.onDetach();Log.i(TAG,"onDetach");}}greendao 与Glide的引用:compile 'com.github.bumptech.glide:glide:3.7.0'compile 'org.greenrobot:greendao:3.0.1'compile 'org.greenrobot:greendao-generator:3.0.0'关于不会用greendao的使用可以使用sqlite替代或者看下greendao的教程 早晚都是要用的 可以去这个看看写的挺详细的http://blog.****.net/****_mm/article/details/78212736
公司项目不好贴出demo
有问题直接微信:17600065050问我就行