android实现文件排序

1、仅仅实现文件的排序功能并不难。首先看看实现的效果图


2、代码图


3、首先实现文件信息保存类,一般有文件大小、时间、文件路径、等

package com.example.apple.myscdn;

/**
 * Created by apple on 17/5/10.
 */

public class FileInfo {
    private int fileImage;
    private String fileSize;//文件大小
    private long fileS;
    private String fileTime;//文件时间
    private String fileName;//文件名字
    private String filePath;//文件路径
    private String lastPath;//上一级目录名字
    private int FileNum;//子文件数
    private boolean canRead;
    private boolean canWrite;
    private boolean selected;
    private boolean isHidden;
    private long ModifiedData;
    private boolean isDir;
    private boolean isFile;

    public FileInfo() {
    }

    public FileInfo(int fileImage, String fileSize, long fileS, String fileTime, String fileName, String filePath, String lastPath, int fileNum, boolean canRead, boolean canWrite, boolean selected, boolean isHidden, long modifiedData, boolean isDir, boolean isFile) {
        this.fileImage = fileImage;
        this.fileSize = fileSize;
        this.fileS = fileS;
        this.fileTime = fileTime;
        this.fileName = fileName;
        this.filePath = filePath;
        this.lastPath = lastPath;
        FileNum = fileNum;
        this.canRead = canRead;
        this.canWrite = canWrite;
        this.selected = selected;
        this.isHidden = isHidden;
        ModifiedData = modifiedData;
        this.isDir = isDir;
        this.isFile = isFile;
    }

    public int getFileImage() {
        return fileImage;
    }

    public void setFileImage(int fileImage) {
        this.fileImage = fileImage;
    }

    public String getFileSize() {
        return fileSize;
    }

    public void setFileSize(String fileSize) {
        this.fileSize = fileSize;
    }

    public long getFileS() {
        return fileS;
    }

    public void setFileS(long fileS) {
        this.fileS = fileS;
    }

    public String getFileTime() {
        return fileTime;
    }

    public void setFileTime(String fileTime) {
        this.fileTime = fileTime;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public String getLastPath() {
        return lastPath;
    }

    public void setLastPath(String lastPath) {
        this.lastPath = lastPath;
    }

    public int getFileNum() {
        return FileNum;
    }

    public void setFileNum(int fileNum) {
        FileNum = fileNum;
    }

    public boolean isCanRead() {
        return canRead;
    }

    public void setCanRead(boolean canRead) {
        this.canRead = canRead;
    }

    public boolean isCanWrite() {
        return canWrite;
    }

    public void setCanWrite(boolean canWrite) {
        this.canWrite = canWrite;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    public boolean isHidden() {
        return isHidden;
    }

    public void setHidden(boolean hidden) {
        isHidden = hidden;
    }

    public long getModifiedData() {
        return ModifiedData;
    }

    public void setModifiedData(long modifiedData) {
        ModifiedData = modifiedData;
    }

    public boolean isDir() {
        return isDir;
    }

    public void setDir(boolean dir) {
        isDir = dir;
    }

    public boolean isFile() {
        return isFile;
    }

    public void setFile(boolean file) {
        isFile = file;
    }

    @Override
    public String toString() {
        return "FileInfo{" +
                "fileImage=" + fileImage +
                ", fileSize='" + fileSize + '\'' +
                ", fileS=" + fileS +
                ", fileTime='" + fileTime + '\'' +
                ", fileName='" + fileName + '\'' +
                ", filePath='" + filePath + '\'' +
                ", lastPath='" + lastPath + '\'' +
                ", FileNum=" + FileNum +
                ", canRead=" + canRead +
                ", canWrite=" + canWrite +
                ", selected=" + selected +
                ", isHidden=" + isHidden +
                ", ModifiedData=" + ModifiedData +
                ", isDir=" + isDir +
                ", isFile=" + isFile +
                '}';
    }
}

4、排序文件实现、一般有文件大小、名字、类型、和时间排序

package com.example.apple.myscdn;

/**
 * Created by apple on 17/5/10.
 */


import com.example.apple.myscdn.utils.Utils;

import java.util.Comparator;
import java.util.HashMap;

public class FileSortHelper {


    public enum SortMethod {
        name, size, date, type
    }

    private SortMethod mSort;

    private boolean mFileFirst;

    private HashMap<SortMethod, Comparator> mComparatorList = new HashMap<>();

    public FileSortHelper() {
        mSort = SortMethod.name;
        mComparatorList.put(SortMethod.name, cmpName);
        mComparatorList.put(SortMethod.size, cmpSize);
        mComparatorList.put(SortMethod.date, cmpDate);
        mComparatorList.put(SortMethod.type, cmpType);
    }

    public void setSortMethog(SortMethod s) {
        mSort = s;
    }

    public SortMethod getSortMethod() {
        return mSort;
    }

    public void setFileFirst(boolean f) {
        mFileFirst = f;
    }

    public Comparator getComparator() {
        return mComparatorList.get(mSort);
    }

    private abstract class FileComparator implements Comparator<FileInfo> {

        @Override
        public int compare(FileInfo object1, FileInfo object2) {
            if (object1.isDir() == object2.isDir()) {
                return doCompare(object1, object2);
            }

            if (mFileFirst) {
                // the files are listed before the dirs
                return (object1.isDir() ? 1 : -1);
            } else {
                // the dir-s are listed before the files
                return object1.isDir() ? -1 : 1;
            }
        }

        protected abstract int doCompare(FileInfo object1, FileInfo object2);
    }

    public Comparator cmpName = new FileComparator() {
        @Override
        public int doCompare(FileInfo object1, FileInfo object2) {
            return object1.getFileName().compareToIgnoreCase(object2.getFileName());
        }
    };

    public Comparator cmpSize = new FileComparator() {
        @Override
        public int doCompare(FileInfo object1, FileInfo object2) {
            return longToCompareInt(object1.getFileS() - object2.getFileS());
        }
    };

    public Comparator cmpDate = new FileComparator() {
        @Override
        public int doCompare(FileInfo object1, FileInfo object2) {
            return longToCompareInt(object2.getModifiedData() - object1.getModifiedData());
        }
    };

    private int longToCompareInt(long result) {
        return result > 0 ? 1 : (result < 0 ? -1 : 0);
    }

    public Comparator cmpType = new FileComparator() {
        @Override
        public int doCompare(FileInfo object1, FileInfo object2) {
            int result = Utils.getExtFromFilename(object1.getFileName()).compareToIgnoreCase(
                    Utils.getExtFromFilename(object2.getFileName()));
            if (result != 0)
                return result;

            return Utils.getNameFromFilename(object1.getFileName()).compareToIgnoreCase(
                    Utils.getNameFromFilename(object2.getFileName()));
        }
    };

}
5、实现数据的获取,一般可以通过文件路径也可以通过ContentResolver获取,根据个人实际需求写。

 public ArrayList<FileInfo> queryFile(String path, final FileSortHelper sortMethod) {

        fileInfo.clear();
        if (path != null) {
            File file = new File(path);
            File[] files = file.listFiles();
            if (files != null) {
                // Arrays.sort(files);
                if (!file.exists())
                    return null;
                for (File f : files) {
                    //  String absolutePath = f.getAbsolutePath();
                    saveData(f);
                }
                Collections.sort(fileInfo, sortMethod.getComparator());
            }
        }

        return fileInfo;
    }


    /**
     * 将查询数据保存到FileInfo
     *
     * @param f
     */
    private void saveData(File f) {
        FileInfo fi = new FileInfo();
        //if (!f.getName().substring(0, 1).equals(".")) {//去掉.开头文件
        try {
            fi.setFileName(f.getName());
            fi.setFilePath(f.getPath());
            fi.setFileSize(Utils.FormatFileSize(f.length()));
            fi.setFileTime(Utils.LongTimeToStr(f.lastModified()));
            fi.setFileNum(Utils.getFileNum(f.getPath()));
            fi.setDir(f.isDirectory());
            fi.setHidden(f.isHidden());
            fi.setModifiedData(f.lastModified());
            fi.setCanRead(f.canRead());
            fi.setCanWrite(f.canWrite());
            fi.setFileS(f.length());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  }
        fileInfo.add(fi);
    }
ContentResolver获取

/**
     * 根据文件类型,和排序方式查找文件
     *
     * @param fileCategory
     * @param sortMethod
     * @return
     */
    public ArrayList<FileInfo> query(FileCategory fileCategory, SortMethod sortMethod) {
        Uri uri = getContentUriByCategory(fileCategory);
        String selection = buildSelectionByCategory(fileCategory);
        String sortOrder = buildSortOrder(sortMethod);
        if (uri == null) {
            return null;
        }

        String[] projection = new String[]{
                MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.DATE_MODIFIED
        };
        ContentResolver resolver = context.getContentResolver();
        /**
         * 参数:
         uri,指定查询某个应用程序下的某一张表。
         projection, 指定查询的列名。
         selection, 指定where的约束条件。行
         selectionArgs,为where中的占位符提供具体的值。
         orderBy, 指定查询结果的排序方式。
         */
        Cursor cursor = resolver.query(uri, projection, selection, null, sortOrder);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                File f = new File(cursor.getString(1));
                saveData(f);
            }
        }
        return fileInfo;
    }
完整代码
package com.example.apple.myscdn;


import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.example.apple.myscdn.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;

/**
 * Created by 550211 on 2017/4/24.
 */

public class FileCategoryHelper {
    private final String TAG = "FileCategoryHelper";

    //存储文件数据
    private ArrayList<FileInfo> fileInfo = new ArrayList<>();

    private Context context;
    public static String sZipFileMimeType = "application/zip";

    public FileCategoryHelper(Context context) {
        this.context = context;
    }

    /**
     * 文件类型
     */
    public enum FileCategory {
        Picture, Video, Music, Doc, Zip, Apk, Bluetooth, Download, Collection, All, Lately, Other, Theme
    }

    /**
     * 排序方式
     */
    public enum SortMethod {
        name, size, date, type
    }

    /**
     * 根据文件类型,和排序方式查找文件
     *
     * @param fileCategory
     * @param sortMethod
     * @return
     */
    public ArrayList<FileInfo> query(FileCategory fileCategory, SortMethod sortMethod) {
        Uri uri = getContentUriByCategory(fileCategory);
        String selection = buildSelectionByCategory(fileCategory);
        String sortOrder = buildSortOrder(sortMethod);
        if (uri == null) {
            return null;
        }

        String[] projection = new String[]{
                MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.DATE_MODIFIED
        };
        ContentResolver resolver = context.getContentResolver();
        /**
         * 参数:
         uri,指定查询某个应用程序下的某一张表。
         projection, 指定查询的列名。
         selection, 指定where的约束条件。行
         selectionArgs,为where中的占位符提供具体的值。
         orderBy, 指定查询结果的排序方式。
         */
        Cursor cursor = resolver.query(uri, projection, selection, null, sortOrder);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                File f = new File(cursor.getString(1));
                saveData(f);
            }
        }
        return fileInfo;
    }

    public ArrayList<FileInfo> queryFile(String path, final FileSortHelper sortMethod) {

        fileInfo.clear();
        if (path != null) {
            File file = new File(path);
            File[] files = file.listFiles();
            if (files != null) {
                // Arrays.sort(files);
                if (!file.exists())
                    return null;
                for (File f : files) {
                    //  String absolutePath = f.getAbsolutePath();
                    saveData(f);
                }
                Collections.sort(fileInfo, sortMethod.getComparator());
            }
        }

        return fileInfo;
    }


    /**
     * 将查询数据保存到FileInfo
     *
     * @param f
     */
    private void saveData(File f) {
        FileInfo fi = new FileInfo();
        //if (!f.getName().substring(0, 1).equals(".")) {//去掉.开头文件
        try {
            fi.setFileName(f.getName());
            fi.setFilePath(f.getPath());
            fi.setFileSize(Utils.FormatFileSize(f.length()));
            fi.setFileTime(Utils.LongTimeToStr(f.lastModified()));
            fi.setFileNum(Utils.getFileNum(f.getPath()));
            fi.setDir(f.isDirectory());
            fi.setHidden(f.isHidden());
            fi.setModifiedData(f.lastModified());
            fi.setCanRead(f.canRead());
            fi.setCanWrite(f.canWrite());
            fi.setFileS(f.length());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  }
        fileInfo.add(fi);
    }

    private Uri getContentUriByCategory(FileCategory cat) {
        Uri uri;
        String volumeName = "external";
        switch (cat) {
            case Collection:
            case Doc:
            case Zip:
            case Apk:
                uri = MediaStore.Files.getContentUri(volumeName);
                break;
            case Music:
                uri = MediaStore.Audio.Media.getContentUri(volumeName);
                break;
            case Video:
                uri = MediaStore.Video.Media.getContentUri(volumeName);
                break;
            case Picture:
                uri = MediaStore.Images.Media.getContentUri(volumeName);
                break;
            default:
                uri = null;
        }
        return uri;
    }

    private String buildSelectionByCategory(FileCategory cat) {
        String selection = null;
        switch (cat) {
            case Theme:
                selection = MediaStore.Files.FileColumns.DATA + " LIKE '%.mtz'";
                break;
            case Doc:
                selection = buildDocSelection();
                break;
            case Zip:
                selection = "(" + MediaStore.Files.FileColumns.MIME_TYPE + " == '" + sZipFileMimeType + "')";
                break;
            case Apk:
                selection = MediaStore.Files.FileColumns.DATA + " LIKE '%.apk'";
                break;
            default:
                selection = null;
        }
        return selection;
    }

    private String buildDocSelection() {
        StringBuilder selection = new StringBuilder();
        Iterator<String> iter = sDocMimeTypesSet.iterator();
        while (iter.hasNext()) {
            selection.append("(" + MediaStore.Files.FileColumns.MIME_TYPE + "=='" + iter.next() + "') OR ");
        }
        return selection.substring(0, selection.lastIndexOf(")") + 1);
    }

    public static HashSet<String> sDocMimeTypesSet = new HashSet<String>() {
        {
            add("text/plain");
            add("application/pdf");
            add("application/msword");
            add("application/vnd.ms-powerpointl");
            add("application/vnd.ms-excel");

//            add("text/plain");
//            add("text/plain");
//            add("application/pdf");
//            add("application/msword");
//            add("application/vnd.ms-excel");
//            add("application/vnd.ms-excel");
        }
    };

    private String buildSortOrder(SortMethod sort) {
        String sortOrder = null;
        switch (sort) {
            case name:
                sortOrder = MediaStore.Files.FileColumns.TITLE + " asc";
                break;
            case size:
                sortOrder = MediaStore.Files.FileColumns.SIZE + " asc";
                break;
            case date:
                sortOrder = MediaStore.Files.FileColumns.DATE_MODIFIED + " desc";
                break;
            case type:
                sortOrder = MediaStore.Files.FileColumns.MIME_TYPE + " asc, " + MediaStore.Files.FileColumns.TITLE + " asc";
                break;
        }
        return sortOrder;
    }

   
}

6、使用sharedPreference存储排序方式,避免刷新后改变

package com.example.apple.myscdn;

import android.content.Context;
import android.content.SharedPreferences;

import static android.content.Context.MODE_PRIVATE;

/**
 * Created by apple on 17/5/10.
 */

public class SPInfo {
    public static void saveSort(Context context,int type){
        SharedPreferences sp = context.getSharedPreferences("name",MODE_PRIVATE);
        SharedPreferences.Editor editor= sp.edit();
        editor.putInt("name",type);
        editor.commit();
    }

    public static int getSort(Context context){
        SharedPreferences sp = context.getSharedPreferences("name",MODE_PRIVATE);
        return sp.getInt("name",0);
    }
}
7、定义的一些常量代码

package com.example.apple.myscdn.utils;

/**
 * Created by apple on 17/5/10.
 */

public class Type {
    public static final int ID_SORT_NAME_ASC = 20;
    public static final int ID_SORT_NAME_DEC = 21;
    public static final int ID_SORT_TYPE_ASC = 22;
    public static final int ID_SORT_TYPE_DEC = 23;
    public static final int ID_SORT_SIZE_ASC = 24;
    public static final int ID_SORT_SIZE_DEC = 25;
    public static final int ID_SORT_TIME_ASC = 26;
    public static final int ID_SORT_TIME_DEC = 27;

    public static final int START_PROGRESS = 1000;
    public static final int CLOSE_PROGRESS = 1001;

    public static final int UPDATE_LIST = 1002;
    public static final int SHOW_TOP_PATH = 1003;
    public static final String ALL_PATH = "/mnt/sdcard";
    public static final String DOWNLOAD_PATH = "/mnt/sdcard/download";

    public static final int IMAGE = 0;
    public static final int VIDEO = 1;
    public static final int MUSIC = 2;
    public static final int DOC = 3;
    public static final int ZIP=4;
    public static final int APK = 5;
    public static final int BLUETOOTH=6;
    public static final int DOWNLOAD =7;
    public static final int COLLECTION=8;
    public static final int ALL = 9;
    public static final int LATELY = 10;
    public static final int OTHER = 11;
}

8、使用RecycleView分割线代码,可根据实际需求是否添加

package com.example.apple.myscdn.utils;

/**
 * Created by apple on 17/5/10.
 */

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * This class is from the v7 samples of the Android SDK. It's not by me!
 * <p/>
 * See the license above for details.
 */
public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private static final int[] ATTRS = new int[]{
            android.R.attr.listDivider
    };

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

    private Drawable mDivider;

    private int mOrientation;

    public DividerItemDecoration(Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }

    public void setOrientation(int orientation) {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent) {

        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }

    }

    public void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            android.support.v7.widget.RecyclerView v = new android.support.v7.widget.RecyclerView(parent.getContext());
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    public void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}
9、adpater代码,只要就是几个控件显示数据

package com.example.apple.myscdn;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;

/**
 * Created by 550211 on 2017/4/25.
 */

public class MyFileCategoryAdapter extends RecyclerView.Adapter<MyFileCategoryAdapter.MyViewHolder> implements View.OnClickListener{
    private final String TAG = "MyFileCategoryAdapter";
    private Context context;
    private ArrayList<FileInfo> fileInfo;
    private OnItemClickListener mOnItemClickListener = null;

    @Override
    public void onClick(View v) {
        if (mOnItemClickListener != null) {
            mOnItemClickListener.onItemClick(v,(int)v.getTag(),fileInfo.get((int)v.getTag()).getFilePath());
        }
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position, String filePath);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public MyFileCategoryAdapter(Context context, ArrayList<FileInfo> fileInfo) {
        this.context = context;
        this.fileInfo = fileInfo;
    }

    /**
     * update list data
     * @param fileInfo
     */
    public void setData(ArrayList<FileInfo> fileInfo){
        this.fileInfo = fileInfo;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = View.inflate(viewGroup.getContext(), R.layout.item_file_category, null);
        MyViewHolder holder = new MyViewHolder(view);
        view.setOnClickListener(this);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.itemView.setTag(position);
        holder.ivHead.setImageResource(R.drawable.ic_launcher);
        holder.tvFileSize.setText(fileInfo.get(position).getFileSize());
        holder.tvFileTime.setText(fileInfo.get(position).getFileTime());
        holder.tvFileName.setText(fileInfo.get(position).getFileName());

    }

    @Override
    public int getItemCount() {
        if (fileInfo!=null &&fileInfo.size()>0) {
            return fileInfo.size();
        }
        return 0;
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView ivHead;
        TextView tvFileName;
        TextView tvFileTime;
        TextView tvFileSize;


        public MyViewHolder(View itemView) {
            super(itemView);
            ivHead = (ImageView) itemView.findViewById(R.id.iv_head);
            tvFileName = (TextView) itemView.findViewById(R.id.tv_fileName);
            tvFileTime = (TextView) itemView.findViewById(R.id.tv_fileTime);
            tvFileSize = (TextView) itemView.findViewById(R.id.tv_fileSize);

        }
    }
}
布局代码

<?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:gravity="center_vertical"
    android:padding="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:gravity="center"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/iv_head"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY" />
        </LinearLayout>


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_fileName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="七月七日晴"
                />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp">

                <TextView
                    android:id="@+id/tv_fileTime"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="2016/02/11"
                    />

                <TextView
                    android:id="@+id/tv_fileSize"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:text="12.8mb"
                    />
            </LinearLayout>

        </LinearLayout>
    </LinearLayout>

</RelativeLayout>

10、最后实现整体的代码

首先是实现top路径显示的代码,主要是一个textview外加一个HorizontalScrollView实现

 private void showTextPath(String path) {
        String[] spPath = path.split(Type.ALL_PATH);
        StringBuilder sbBuilder = new StringBuilder();
        StringTokenizer tokenizer = new StringTokenizer(spPath[1], "/");
        while (tokenizer.hasMoreTokens()) {
            sbBuilder.append(tokenizer.nextToken() + " > ");
        }

        String likeUsers = sbBuilder.substring(0, sbBuilder.lastIndexOf(">")).toString();
        tvShowPath.setMovementMethod(LinkMovementMethod.getInstance());
        tvShowPath.setText(addClickablePart(likeUsers), TextView.BufferType.SPANNABLE);
    }

    /**
     * 文件头部路径显示
     * @param str
     * @return
     */
    public SpannableStringBuilder addClickablePart(String str){
        SpannableString spanStr = new SpannableString("");
        SpannableStringBuilder ssb = new SpannableStringBuilder(spanStr);
        ssb.append(str) ;

        String[] likeUsers = str.split(">");

        if (likeUsers.length > 0) {
            for (int i = 0; i < likeUsers.length; i++) {
                final String name = likeUsers[i];
                final int start = str.indexOf(name) + spanStr.length();
                ssb.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        if (mCurrentPath != null) {
                            String[] spPath = mCurrentPath.split(removeAllSpace(name));
                            Log.e(TAG, "onClickPath=" + mCurrentPath + "  aa=" + spPath[0]);
                            String newPath = spPath[0] + removeAllSpace(name);
                            mCurrentPath = newPath;//update current path
                            showTextPath(newPath);
                            //refreshFileList(spPath[0] + msg);
                            new RefreshFileThread(spPath[0] + removeAllSpace(name)).start();
                        }
                    }
                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        //  ds.setColor(context.getResources().getColor(R.color.black)); // 设置文本颜色
                        ds.setUnderlineText(false);
                    }
                }, start, start + name.length(), 0);
            }
        }
        return ssb.append("");
    }

    /**
     * 去除空格
     * @param str
     * @return
     */
    public String removeAllSpace(String str) {
        String tmpstr=str.replace(" ","");
        return tmpstr;
    }
当为文件时可用调用系统方法打开

 /**
     * 打开文件
     *
     * @param file
     */
    public void openFile(File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        String type = Utils.getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), type);
        startActivity(intent);
    }
下面实现排序对话框和数据的刷新方法

 public void onSortChanged(FileSortHelper.SortMethod s, String path) {
        if (fileSortHelper.getSortMethod() != s) {
            fileSortHelper.setSortMethog(s);
            //refreshFileList(path);
            new RefreshFileThread(path).start();
        }
    }

    /**
     * show sort list
     */
    public void showDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        final View layout = inflater.inflate(R.layout.dialog_sort, null);//获取自定义布局
        builder.setView(layout);
        // builder.setTitle(R.string.sort);//设置标题内容
        final AlertDialog dlg = builder.create();
        dlg.show();
        RadioGroup rgSort = (RadioGroup) layout.findViewById(R.id.rg_sort);
        Log.e(TAG, "getSort=" + sortType);
        if (SPInfo.getSort(MainActivity.this) == 0) {
            rgSort.check(R.id.rb_name);
        } else {
            sortType = SPInfo.getSort(MainActivity.this);
            switch (sortType) {
                case Type.ID_SORT_NAME_ASC:
                    rgSort.check(R.id.rb_name);
                    break;
                case Type.ID_SORT_TYPE_ASC:
                    rgSort.check(R.id.rb_type);
                    break;
                case Type.ID_SORT_SIZE_ASC:
                    rgSort.check(R.id.rb_size);
                    break;
                case Type.ID_SORT_TIME_ASC:
                    rgSort.check(R.id.rb_time);
                    break;
            }
        }
        rgSort.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_name:
                        sortType = Type.ID_SORT_NAME_ASC;//name
                        onSortChanged(FileSortHelper.SortMethod.name,mCurrentPath);
                        break;
                    case R.id.rb_size:
                        sortType = Type.ID_SORT_SIZE_ASC;//type
                        onSortChanged(FileSortHelper.SortMethod.size,mCurrentPath);
                        break;
                    case R.id.rb_time:
                        sortType = Type.ID_SORT_TIME_ASC;//time
                        onSortChanged(FileSortHelper.SortMethod.name,mCurrentPath);
                        break;
                    case R.id.rb_type:
                        sortType = Type.ID_SORT_TYPE_ASC;//type
                        onSortChanged(FileSortHelper.SortMethod.type,mCurrentPath);
                        break;
                    default:
                        break;
                }
                SPInfo.saveSort(MainActivity.this, sortType);//保存排序方式
                Log.e(TAG, "sortType=" + sortType);
                dlg.dismiss();
            }
        });
    }
    //refresh file
    private void refreshFileList() {
        //if (path != null) {
        //info = fileCategoryHelper.queryFile(path, fileSortHelper);
        adapter.setData(info);
        rvCategory.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        // }
        sendMsg(Type.CLOSE_PROGRESS);
    }
    /**
     * refresh file list thread
     */
    class RefreshFileThread extends Thread {
        private String path;

        public RefreshFileThread(String path) {
            this.path = path;
        }

        @Override
        public void run() {

            if (path != null) {
                sendMsg(Type.START_PROGRESS);
                info = fileCategoryHelper.queryFile(path, fileSortHelper);
                sendMsg(Type.UPDATE_LIST);
            }
        }
    }

    private void sendMsg(int type) {
        Message msg = new Message();
        msg.what = type;
        handler.sendMessage(msg);
    }
完整代码如下,

package com.example.apple.myscdn;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.apple.myscdn.utils.DividerItemDecoration;
import com.example.apple.myscdn.utils.Type;
import com.example.apple.myscdn.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private final String TAG = "MainActivity";

    private RecyclerView rvCategory;
    private ImageView iv_back;
    private TextView tv_title;
    private ImageView iv_search;
    private ImageView iv_more;
    private TextView tvNoFile;
    private RelativeLayout rl_title_bar;
    private LinearLayout llShowPath;
    private TextView tvShowPath;
    private HorizontalScrollView scrollView;
    private TextView tvSdcard;
    private ProgressBar pbUpdate;
    private FileCategoryHelper fileCategoryHelper;

    private int sortType = Type.ID_SORT_NAME_ASC;//初始排序方式
    private String mCurrentPath = "/mnt/sdcard";//current path

    private FileSortHelper fileSortHelper;
    private ArrayList<FileInfo> info;
    private MyFileCategoryAdapter adapter;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case Type.START_PROGRESS:
                    pbUpdate.setVisibility(View.VISIBLE);
                    break;

                case Type.CLOSE_PROGRESS:
                    pbUpdate.setVisibility(View.GONE);
                    break;

                case Type.UPDATE_LIST://update list
                    refreshFileList();
                    break;

                case Type.SHOW_TOP_PATH:
                    llShowPath.setVisibility(View.VISIBLE);
                    break;
            }

            super.handleMessage(msg);
        }
    };

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


        initView();
        fileSortHelper = new FileSortHelper();
        initShow();
    }
    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setOnClickListener(this);
        iv_search = (ImageView) findViewById(R.id.iv_search);
        iv_more = (ImageView) findViewById(R.id.iv_more);
        iv_more.setOnClickListener(this);
        rl_title_bar = (RelativeLayout) findViewById(R.id.rl_title_bar);

        tvSdcard = (TextView) findViewById(R.id.tv_sdcard);
        tvSdcard.setOnClickListener(this);
        llShowPath = (LinearLayout) findViewById(R.id.ll_show_path);
        tvShowPath = (TextView) findViewById(R.id.tv_show_path);
        tvNoFile = (TextView) findViewById(R.id.tv_no_file);
        rvCategory = (RecyclerView) findViewById(R.id.rv_category);
        pbUpdate = (ProgressBar) findViewById(R.id.pb_update);

        scrollView = (HorizontalScrollView) findViewById(R.id.scrollView);


    }

    private void initShow() {
        tv_title.setText("文件排序");
        fileCategoryHelper = new FileCategoryHelper(this);
        info = fileCategoryHelper.queryFile(mCurrentPath, fileSortHelper);

        adapter = new MyFileCategoryAdapter(MainActivity.this, info);
        rvCategory.setHasFixedSize(true);
        // 创建一个线性布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        // 设置布局管理器
        rvCategory.setLayoutManager(layoutManager);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvCategory.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        rvCategory.setAdapter(adapter);

        adapter.setOnItemClickListener(new setOnItemClickListener());

    }

    private void showTextPath(String path) {
        String[] spPath = path.split(Type.ALL_PATH);
        StringBuilder sbBuilder = new StringBuilder();
        StringTokenizer tokenizer = new StringTokenizer(spPath[1], "/");
        while (tokenizer.hasMoreTokens()) {
            sbBuilder.append(tokenizer.nextToken() + " > ");
        }

        String likeUsers = sbBuilder.substring(0, sbBuilder.lastIndexOf(">")).toString();
        tvShowPath.setMovementMethod(LinkMovementMethod.getInstance());
        tvShowPath.setText(addClickablePart(likeUsers), TextView.BufferType.SPANNABLE);
    }

    /**
     * 文件头部路径显示
     * @param str
     * @return
     */
    public SpannableStringBuilder addClickablePart(String str){
        SpannableString spanStr = new SpannableString("");
        SpannableStringBuilder ssb = new SpannableStringBuilder(spanStr);
        ssb.append(str) ;

        String[] likeUsers = str.split(">");

        if (likeUsers.length > 0) {
            for (int i = 0; i < likeUsers.length; i++) {
                final String name = likeUsers[i];
                final int start = str.indexOf(name) + spanStr.length();
                ssb.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        if (mCurrentPath != null) {
                            String[] spPath = mCurrentPath.split(removeAllSpace(name));
                            Log.e(TAG, "onClickPath=" + mCurrentPath + "  aa=" + spPath[0]);
                            String newPath = spPath[0] + removeAllSpace(name);
                            mCurrentPath = newPath;//update current path
                            showTextPath(newPath);
                            //refreshFileList(spPath[0] + msg);
                            new RefreshFileThread(spPath[0] + removeAllSpace(name)).start();
                        }
                    }
                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        //  ds.setColor(context.getResources().getColor(R.color.black)); // 设置文本颜色
                        ds.setUnderlineText(false);
                    }
                }, start, start + name.length(), 0);
            }
        }
        return ssb.append("");
    }

    /**
     * 去除空格
     * @param str
     * @return
     */
    public String removeAllSpace(String str) {
        String tmpstr=str.replace(" ","");
        return tmpstr;
    }

    //short onclick
    class setOnItemClickListener implements MyFileCategoryAdapter.OnItemClickListener {

        @Override
        public void onItemClick(View view, int position, String filePath) {
            mCurrentPath = filePath;
            File file = new File(filePath);
            if (file.exists() && file.canRead() && file.isDirectory()) {
                new RefreshFileThread(filePath).start();
            } else {
                openFile(file);
            }

            if (!mCurrentPath.equals(Type.ALL_PATH) && file.isDirectory()) {
                showTextPath(filePath);
            }

            scrollView.post(new Runnable() {
                public void run() {
                    scrollView.fullScroll(View.FOCUS_RIGHT);
                }
            });
        }
    }

    /**
     * 打开文件
     *
     * @param file
     */
    public void openFile(File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        String type = Utils.getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), type);
        startActivity(intent);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;

            case R.id.iv_more:
                showDialog();
                break;
            case R.id.tv_sdcard:
                //refreshFileList(Type.ALL_PATH);
                new RefreshFileThread(Type.ALL_PATH).start();
                tvShowPath.setText("");
                mCurrentPath = Type.ALL_PATH;//update current path
                break;
        }
    }

    public void onSortChanged(FileSortHelper.SortMethod s, String path) {
        if (fileSortHelper.getSortMethod() != s) {
            fileSortHelper.setSortMethog(s);
            //refreshFileList(path);
            new RefreshFileThread(path).start();
        }
    }

    /**
     * show sort list
     */
    public void showDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        final View layout = inflater.inflate(R.layout.dialog_sort, null);//获取自定义布局
        builder.setView(layout);
        // builder.setTitle(R.string.sort);//设置标题内容
        final AlertDialog dlg = builder.create();
        dlg.show();
        RadioGroup rgSort = (RadioGroup) layout.findViewById(R.id.rg_sort);
        Log.e(TAG, "getSort=" + sortType);
        if (SPInfo.getSort(MainActivity.this) == 0) {
            rgSort.check(R.id.rb_name);
        } else {
            sortType = SPInfo.getSort(MainActivity.this);
            switch (sortType) {
                case Type.ID_SORT_NAME_ASC:
                    rgSort.check(R.id.rb_name);
                    break;
                case Type.ID_SORT_TYPE_ASC:
                    rgSort.check(R.id.rb_type);
                    break;
                case Type.ID_SORT_SIZE_ASC:
                    rgSort.check(R.id.rb_size);
                    break;
                case Type.ID_SORT_TIME_ASC:
                    rgSort.check(R.id.rb_time);
                    break;
            }
        }
        rgSort.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_name:
                        sortType = Type.ID_SORT_NAME_ASC;//name
                        onSortChanged(FileSortHelper.SortMethod.name,mCurrentPath);
                        break;
                    case R.id.rb_size:
                        sortType = Type.ID_SORT_SIZE_ASC;//type
                        onSortChanged(FileSortHelper.SortMethod.size,mCurrentPath);
                        break;
                    case R.id.rb_time:
                        sortType = Type.ID_SORT_TIME_ASC;//time
                        onSortChanged(FileSortHelper.SortMethod.name,mCurrentPath);
                        break;
                    case R.id.rb_type:
                        sortType = Type.ID_SORT_TYPE_ASC;//type
                        onSortChanged(FileSortHelper.SortMethod.type,mCurrentPath);
                        break;
                    default:
                        break;
                }
                SPInfo.saveSort(MainActivity.this, sortType);//保存排序方式
                Log.e(TAG, "sortType=" + sortType);
                dlg.dismiss();
            }
        });
    }
    //refresh file
    private void refreshFileList() {
        //if (path != null) {
        //info = fileCategoryHelper.queryFile(path, fileSortHelper);
        adapter.setData(info);
        rvCategory.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        // }
        sendMsg(Type.CLOSE_PROGRESS);
    }
    /**
     * refresh file list thread
     */
    class RefreshFileThread extends Thread {
        private String path;

        public RefreshFileThread(String path) {
            this.path = path;
        }

        @Override
        public void run() {

            if (path != null) {
                sendMsg(Type.START_PROGRESS);
                info = fileCategoryHelper.queryFile(path, fileSortHelper);
                sendMsg(Type.UPDATE_LIST);
            }
        }
    }

    private void sendMsg(int type) {
        Message msg = new Message();
        msg.what = type;
        handler.sendMessage(msg);
    }
}

布局代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.a550211.mycsdn.MainActivity">

    <include layout="@layout/title_bar" />
    <LinearLayout
        android:id="@+id/ll_show_path"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp">

        <TextView
            android:id="@+id/tv_sdcard"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="内部存储设备 > " />


        <HorizontalScrollView
            android:id="@+id/scrollView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="none">

            <TextView
                android:id="@+id/tv_show_path"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </HorizontalScrollView>

    </LinearLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_category"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"></android.support.v7.widget.RecyclerView>

        <TextView
            android:id="@+id/tv_no_file"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="没有任何文件"
            android:visibility="gone" />

        <ProgressBar
            android:id="@+id/pb_update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="gone" />
    </RelativeLayout>
</LinearLayout>

排序对话框布局代码实现

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:padding="10dp"
        android:textSize="23dp"
        android:gravity="center"
        android:layout_width="match_parent"
        android:text="排序"
        android:layout_height="wrap_content" />

    <RadioGroup
        android:id="@+id/rg_sort"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/rb_name"
            android:layout_width="fill_parent"
            android:layout_height="50dip"
            android:button="@null"
            android:drawableRight="@android:drawable/btn_radio"
            android:paddingLeft="30dip"
            android:text="名称"
            android:textSize="20dip" />

        <RadioButton
            android:id="@+id/rb_time"
            android:layout_width="fill_parent"
            android:layout_height="50dip"
            android:button="@null"
            android:drawableRight="@android:drawable/btn_radio"
            android:paddingLeft="30dip"
            android:text="时间"
            android:textSize="20dip" />

        <RadioButton
            android:id="@+id/rb_type"
            android:layout_width="fill_parent"
            android:layout_height="50dip"
            android:button="@null"
            android:drawableRight="@android:drawable/btn_radio"
            android:paddingLeft="30dip"
            android:text="类型"
            android:textSize="20dip" />

        <RadioButton
            android:id="@+id/rb_size"
            android:layout_width="fill_parent"
            android:layout_height="50dip"
            android:button="@null"
            android:drawableRight="@android:drawable/btn_radio"
            android:paddingLeft="30dip"
            android:text="大小"
            android:textSize="20dip" />

    </RadioGroup>

</LinearLayout>

title_bar.xml代码

<?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="51dp"
    android:gravity="center_vertical"
    android:id="@+id/rl_title_bar"
    android:padding="5dp">

    <LinearLayout
        android:id="@+id/ll_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="12dp"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/iv_back"
            android:layout_width="12dp"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:text="文件管理"
            android:textSize="18sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="12dp"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/iv_search"
            android:layout_width="25dp"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />

        <ImageView
            android:id="@+id/iv_more"
            android:layout_width="25dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>
</RelativeLayout>

utils的代码

package com.example.apple.myscdn.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by apple on 17/5/10.
 */

public class Utils {
    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    public static String FormatFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 将毫秒转特定时间格式
     *
     * @param time
     * @return
     */
    public static String LongTimeToStr(long time) {
        int m = 1000;
        int f = m * 60;
        int h = f * 60;
        Date date = new Date(time);

        if (time < h * f * m) {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            return sdf.format(date);
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            return sdf.format(date);
        }
    }

    /**
     * 获取文件数量
     *
     * @param path
     * @return
     */
    public static int getFileNum(String path) {
        File file = new File(path);
        int fileNum = 0;
        File[] fileArray = file.listFiles();
        if (fileArray!=null) {
            for (File f : fileArray) {
                if (f.isFile() || f.isDirectory() && !f.isHidden()) {
                    fileNum++;
                }
            }
        }
        return fileNum;
    }

    /**
     * 获取文件大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists() && !file.isDirectory()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    /*
* 采用了新的办法获取APK图标,之前的失败是因为android中存在的一个BUG,通过
* appInfo.publicSourceDir = apkPath;来修正这个问题,详情参见:
* http://code.google.com/p/android/issues/detail?id=9151
*/
    public static Drawable getApkIcon(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath,
                PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;
            appInfo.sourceDir = apkPath;
            appInfo.publicSourceDir = apkPath;
            try {
                return appInfo.loadIcon(pm);
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String getMIMEType(File f) {
        String type = "";
        String fileName = f.getName();
        String ext = fileName.substring(fileName.lastIndexOf(".")
                + 1, fileName.length()).toLowerCase();

        if (ext.equals("jpg") || ext.equals("jpeg") || ext.equals("gif")
                || ext.equals("png") || ext.equals("bmp") || ext.equals("wbmp")) {
            type = "image/*";
        } else if (ext.equals("mp3") || ext.equals("amr") || ext.equals("wma")
                || ext.equals("aac") || ext.equals("m4a") || ext.equals("mid")
                || ext.equals("xmf") || ext.equals("ogg") || ext.equals("wav")
                || ext.equals("qcp") || ext.equals("awb") || ext.equals("flac") || ext.equals("3gpp")) {
            type = "audio/*";
        } else if (ext.equals("3gp") || ext.equals("avi") || ext.equals("mp4")
                || ext.equals("3g2") || ext.equals("wmv") || ext.equals("divx")
                || ext.equals("mkv") || ext.equals("webm") || ext.equals("ts")
                || ext.equals("asf") || ext.equals("flv") || ext.equals("mov") || ext.equals("mpg")) {
            type = "video/*";
        } else if (ext.equals("apk")) {
            type = "application/vnd.android.package-archive";
        } else if (ext.equals("vcf")) {
            type = "text/x-vcard";
        } else if (ext.equals("txt")) {
            type = "text/plain";
        } else if (ext.equals("doc") || ext.equals("docx")) {
            type = "application/msword";
        } else if (ext.equals("xls") || ext.equals("xlsx")) {
            type = "application/vnd.ms-excel";
        } else if (ext.equals("ppt") || ext.equals("pptx")) {
            type = "application/vnd.ms-powerpoint";
        } else if (ext.equals("pdf")) {
            type = "application/pdf";
        } else if (ext.equals("xml")) {
            type = "text/xml";
        } else if (ext.equals("html")) {
            type = "text/html";
        } else if (ext.equals("zip")) {
            type = "application/zip";
        } else {
            type = "application/octet-stream";
        }

        return type;
    }

    public static String getExtFromFilename(String filename) {
        int dotPosition = filename.lastIndexOf('.');
        if (dotPosition != -1) {
            return filename.substring(dotPosition + 1, filename.length());
        }
        return "";
    }

    public static String getNameFromFilename(String filename) {
        int dotPosition = filename.lastIndexOf('.');
        if (dotPosition != -1) {
            return filename.substring(0, dotPosition);
        }
        return "";
    }
}


需要用到权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>

记得还要添加recycleview.jar包
compile files('libs/android-support-v7-recyclerview.jar')

代码有点多,需要可慢慢看:










  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值