• 模拟手机文件管理之查看与选择功能


    Activity:

    package com.example.zjc_file_choice.activity;
    
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    
    import com.example.zjc_file_choice.R;
    
    import android.app.ListActivity;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.View;
    import android.view.Window;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemLongClickListener;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;
    
    /**
     * 文件选择不需要权限。该Activity可以选择文件,也可以打开文件
     * 
     * @author Zjc121327
     * @data 2015/02/06
     * 
     */
    public class MyFileManagerActivity extends ListActivity {
        /** 文件名称集合 */
        private List<String> items = null;
    
        /** 文件绝对路径集合 */
        private List<String> paths = null;
    
        /** 根目录,路径 */
        private String rootPath;
    
        /** 当前目录,路径 */
        private TextView mPath;
    
        /** 文件选择的状态 :true为选择状态 */
        private boolean selectState = false;
    
        /** 选中文件的绝对路径集合 */
        private List<String> mSelectedFilePaths = new ArrayList<String>();
    
        @Override
        protected void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.activity_file_manager);
            rootPath = SDCardFetchUtils.getSDCardPath() + "/";
            mPath = (TextView) findViewById(R.id.mPath);
            getFileDir(rootPath);
            getListView().setOnItemLongClickListener(longClickListener);
        }
    
        /**
         * 根据文件夹的绝对路径获取文件夹里面的文件
         * 
         * @param filePath
         *            文件夹的绝对路径
         */
        private void getFileDir(String filePath) {
            mPath.setText("存储目录:" + filePath);
            items = new ArrayList<String>();
            paths = new ArrayList<String>();
            File f = new File(filePath);
            if (!f.exists()) {
                f.mkdirs();
            }
            File[] files = f.listFiles();
            if (!filePath.equals(rootPath)) {
                items.add("b1");
                paths.add(rootPath);
                items.add("b2");
                paths.add(f.getParent());
            }
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    File file = files[i];
                    items.add(file.getName());
                    paths.add(file.getPath());
                }
            } else {
                Toast.makeText(getApplicationContext(), "该文件夹中没有文件",
                        Toast.LENGTH_LONG).show();
            }
            setListAdapter(new FileFolderAdapter(this, items, paths));
        }
    
        private OnItemLongClickListener longClickListener = new OnItemLongClickListener() {
    
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                    int position, long id) {
                File file = new File(paths.get(position));
                if (!file.isDirectory()) {
                    if (!mSelectedFilePaths.contains(paths.get(position))) {
                        mSelectedFilePaths.add(paths.get(position));
                        view.setBackgroundColor(getResources().getColor(
                                R.color.white_gray));
                        ImageView selected = (ImageView) view
                                .findViewById(R.id.selected);
                        selected.setVisibility(View.VISIBLE);
                        selectState = true;// 设置处于文件选择状态
                    } else {
                        Toast.makeText(getApplicationContext(), "该文件已选择",
                                Toast.LENGTH_LONG).show();
                    }
                } else {
                    getFileDir(file.getAbsolutePath());
                }
                return true;
            }
        };
    
        @Override
        protected void onListItemClick(ListView l, View v, int position, long id) {
            File file = new File(paths.get(position));
            // 不是文件选择状态时
            if (!selectState) {
                // 判断是否为文件夹
                if (file.isDirectory()) {
                    getFileDir(paths.get(position));
                } else {
                    openFile(file);
                }
    
            } else {
                if (!file.isDirectory()) {
                    // 如果文件存在
                    if (mSelectedFilePaths.contains(paths.get(position))) {
                        mSelectedFilePaths.remove(paths.get(position));
                        v.setBackgroundColor(getResources().getColor(R.color.white));
                        ImageView selected = (ImageView) v
                                .findViewById(R.id.selected);
                        selected.setVisibility(View.GONE);
                    } else {// 如果不在
                        mSelectedFilePaths.add(paths.get(position));
                        v.setBackgroundColor(getResources().getColor(
                                R.color.white_gray));
                        ImageView selected = (ImageView) v
                                .findViewById(R.id.selected);
                        selected.setVisibility(View.VISIBLE);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "文件选择状态时,文件夹不能被选择",
                            Toast.LENGTH_LONG).show();
                }
            }
    
            if (mSelectedFilePaths.size() == 0) {
                // 取消选择状态
                selectState = false;
            }
        }
    
        /**
         * 打开文件
         * 
         * @param file
         *            被打开文件的绝对路径
         */
        private void openFile(File file) {
            // Uri uri = Uri.parse("file://"+file.getAbsolutePath());
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // 设置intent的Action属性
            intent.setAction(Intent.ACTION_VIEW);
            // 获取文件file的MIME类型
            String type = getMIMEType(file);
            // 设置intent的data和Type属性。
            intent.setDataAndType(/* uri */Uri.fromFile(file), type);
            // 跳转
            startActivity(intent);
        }
    
        /**
         * 根据文件后缀名获得对应的MIME类型。
         * 
         * @param file
         *            文件的绝对路径
         */
        private String getMIMEType(File file) {
            String type = "*/*";
            String fName = file.getName();
            // 获取后缀名前的分隔符"."在fName中的位置。
            int dotIndex = fName.lastIndexOf(".");
            if (dotIndex < 0) {
                return type;
            }
            /* 获取文件的后缀名 */
            String end = fName.substring(dotIndex, fName.length()).toLowerCase();
            if (end == "")
                return type;
            // 在MIME和文件类型的匹配表中找到对应的MIME类型。
            for (int i = 0; i < MIME_MapTable.length; i++) {
                if (end.equals(MIME_MapTable[i][0]))
                    type = MIME_MapTable[i][1];
            }
            return type;
        }
    
        // 建立一个MIME类型与文件后缀名的匹配表
        private final String[][] MIME_MapTable = {
                // {后缀名, MIME类型}
                { ".3gp", "video/3gpp" },
                { ".apk", "application/vnd.android.package-archive" },
                { ".asf", "video/x-ms-asf" }, { ".avi", "video/x-msvideo" },
                { ".bin", "application/octet-stream" }, { ".bmp", "image/bmp" },
                { ".c", "text/plain" }, { ".class", "application/octet-stream" },
                { ".conf", "text/plain" }, { ".cpp", "text/plain" },
                { ".doc", "application/msword" },
                { ".exe", "application/octet-stream" }, { ".gif", "image/gif" },
                { ".gtar", "application/x-gtar" }, { ".gz", "application/x-gzip" },
                { ".h", "text/plain" }, { ".htm", "text/html" },
                { ".html", "text/html" }, { ".jar", "application/java-archive" },
                { ".java", "text/plain" }, { ".jpeg", "image/jpeg" },
                { ".jpg", "image/jpeg" }, { ".js", "application/x-javascript" },
                { ".log", "text/plain" }, { ".m3u", "audio/x-mpegurl" },
                { ".m4a", "audio/mp4a-latm" }, { ".m4b", "audio/mp4a-latm" },
                { ".m4p", "audio/mp4a-latm" }, { ".m4u", "video/vnd.mpegurl" },
                { ".m4v", "video/x-m4v" }, { ".mov", "video/quicktime" },
                { ".mp2", "audio/x-mpeg" }, { ".mp3", "audio/x-mpeg" },
                { ".mp4", "video/mp4" },
                { ".mpc", "application/vnd.mpohun.certificate" },
                { ".mpe", "video/mpeg" }, { ".mpeg", "video/mpeg" },
                { ".mpg", "video/mpeg" }, { ".mpg4", "video/mp4" },
                { ".mpga", "audio/mpeg" },
                { ".msg", "application/vnd.ms-outlook" }, { ".ogg", "audio/ogg" },
                { ".pdf", "application/pdf" }, { ".png", "image/png" },
                { ".pps", "application/vnd.ms-powerpoint" },
                { ".ppt", "application/vnd.ms-powerpoint" },
                { ".prop", "text/plain" },
                { ".rar", "application/x-rar-compressed" },
                { ".rc", "text/plain" }, { ".rmvb", "audio/x-pn-realaudio" },
                { ".rtf", "application/rtf" }, { ".sh", "text/plain" },
                { ".tar", "application/x-tar" },
                { ".tgz", "application/x-compressed" }, { ".txt", "text/plain" },
                { ".wav", "audio/x-wav" }, { ".wma", "audio/x-ms-wma" },
                { ".wmv", "audio/x-ms-wmv" },
                { ".wps", "application/vnd.ms-works" },
                // {".xml", "text/xml"},
                { ".xml", "text/plain" }, { ".z", "application/x-compress" },
                { ".zip", "application/zip" }, { "", "*/*" } };
    
    }

    Adapter:

    package com.example.zjc_file_choice.activity;
    
    import java.io.File;
    import java.util.List;
    
    import com.example.zjc_file_choice.R;
    
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    /**
     * 显示文件(夹)适配器 文件选择适配器
     * 
     * @author Zjc
     * @data 2015/02/06
     * 
     */
    public class FileFolderAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private Bitmap mIcon1;
        private Bitmap mIcon2;
        private Bitmap mIcon3;
        private Bitmap mIcon4;
        private List<String> items;
        private List<String> paths;
    
        public FileFolderAdapter(Context context, List<String> it, List<String> pa) {
            mInflater = LayoutInflater.from(context);
            items = it;
            paths = pa;
            mIcon1 = BitmapFactory.decodeResource(context.getResources(),
                    R.drawable.ic_back_dir);// 返回根目录
            mIcon2 = BitmapFactory.decodeResource(context.getResources(),
                    R.drawable.ic_back_up);// 返回上一层
            mIcon3 = BitmapFactory.decodeResource(context.getResources(),
                    R.drawable.ic_folder);// 文件夹
            mIcon4 = BitmapFactory.decodeResource(context.getResources(),
                    R.drawable.ic_doc);// 文件
        }
    
        @Override
        public int getCount() {
            return items.size();
        }
    
        @Override
        public Object getItem(int position) {
            return items.get(position);
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater
                        .inflate(R.layout.list_item_for_folder, null);
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.text);
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);
                holder.selected = (ImageView) convertView
                        .findViewById(R.id.selected);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            File f = new File(paths.get(position).toString());
            if (items.get(position).toString().equals("b1")) {
                holder.text.setText("返回根目录");
                holder.icon.setImageBitmap(mIcon1);
            } else if (items.get(position).toString().equals("b2")) {
                holder.text.setText("返回上一层");
                holder.icon.setImageBitmap(mIcon2);
            } else {
                holder.text.setText(f.getName());
                if (f.isDirectory()) {
                    holder.icon.setImageBitmap(mIcon3);
                } else {
                    holder.icon.setImageBitmap(mIcon4);
                }
            }
            return convertView;
        }
    
        private class ViewHolder {
            TextView text;
            ImageView icon;
            ImageView selected;
        }
    }

    XML文件:activity_file_manager.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#FFFFFF"
        android:orientation="vertical" >
    
        <TextView
            android:id="@+id/mPath"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:padding="5dp"
            android:background="@android:color/darker_gray"
            android:layout_alignParentTop="true"
            android:textColor="#00ff00"
            android:text="目录:"
            android:gravity="center_vertical"
            android:textSize="18sp" >
        </TextView>
    
        <ListView
            android:layout_below="@+id/mPath"
            android:id="@android:id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:listSelector="#9e9e9e" >
        </ListView>
    
        <LinearLayout
            android:visibility="gone"
            android:layout_alignParentBottom="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFFFFF"
            android:gravity="center"
            android:orientation="horizontal" >
    
            <Button
                android:id="@+id/buttonConfirm"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="确定" />
    
            <Button
                android:id="@+id/buttonCancle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="取消" />
        </LinearLayout>
    
    </RelativeLayout>

    XML文件:list_item_for_folder.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="45dp"
        android:background="#ffffff"
        android:orientation="horizontal" >
    
        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="45dp"
            android:layout_gravity="center_vertical"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            android:padding="6dp" >
    
            <ImageView
                android:id="@+id/icon"
                android:layout_width="30dip"
                android:layout_height="30dip"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:layout_gravity="center_vertical" >
            </ImageView>
    
            <TextView
                android:id="@+id/text"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:layout_toRightOf="@+id/icon"
                android:gravity="center_vertical"
                android:layout_centerVertical="true"
                android:textColor="#000000" >
            </TextView>
    
            <ImageView
                android:id="@+id/selected"
                android:layout_width="20dip"
                android:layout_height="20dip"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_gravity="center_vertical"
                android:src="@drawable/pictures_selected"
                android:visibility="gone" >
            </ImageView>
        </RelativeLayout>
    
    </LinearLayout>
  • 相关阅读:
    解方程
    十进制快速幂
    comb
    题单解题记录-POJ题目分类推荐 (很好很有层次感)
    算法题离谱错误合集
    VMware-Ubuntu16.04踩坑解决记录
    2020牛客多校赛第三场
    需学习的博客地址
    错误记录
    可持久化线段树 区间第k大/小
  • 原文地址:https://www.cnblogs.com/zjc0514/p/4360309.html
Copyright © 2020-2023  润新知