Android选择文件或文件夹并得到选择路径的程序

2015年02月09日 Android 2条评论 阅读4889次
Android选择文件或文件夹并得到选择路径的程序

实现的功能就是:你需要一个手机本地存储上的一个文件或文件夹的路径,可以浏览并选择。
软件截图
device-2015-02-09-133340.png


遇到了一个很基础简单的问题再次记录当做教训警示自己及其他人:
 作为一条约定来说大家都知道:两个字符串比较要用String的equal方法,不能用==的方法来比较。
 但我在比较当前路径是否为ROOT(给定的初始根路径)时,我便使用了==来判断。
 后来debug过程中发现了这个错误,于是提出了一个方法:
 
private boolean isRootPath(String path) {
        return ROOT.equals(path);
 }

还有一个要注意的是:
选择文件夹画面出来时如果手机做了屏幕翻转的动作,则文件夹选择的路径就回到了给出的初始ROOT路径,之前选择的目录就没有被记下来。
针对此问题,只要在AndroidManifest文件中相应的activity注册时添加android:configChanges属性即可。
完成代码为android:configChanges="orientation|screenSize"
其中android:configChanges后面的值可以自己定义,详细使用可以查阅网络资料。

主要代码:

package com.example.filefolderselector;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import net.jileniao.android.filefolderselecter.R;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * if you want to select one folder, start this Activity as follow.
 * 
 * <pre>
 * Intent intent = new Intent(context, FolderSelecterActivity.class);
 * startActivityForResult(intent, requestCode);
 * </pre>
 * 
 * if you want to select one file, you must specify you need a file, and the
 * file extension obviously. Start the activity like this.
 * 
 * <pre>
 * Intent intent = new Intent(context, FileFolderSelecterActivity.class);
 * intent.putExtra(FileFolderSelecterActivity.FILE_EXTENSION, &quot;mp3&quot;);
 * startActivityForResult(intent, requestCode);
 * </pre>
 * 
 * if you want to select any file,the extension of the file may not be
 * specified, but the file type must be specified obviously. Start the activity
 * like this.
 * 
 * <pre>
 * Intent intent = new Intent(context, FileFolderSelecterActivity.class);
 * intent.putExtra(FileFolderSelecterActivity.FILE_EXTENSION, &quot;mp3&quot;);
 * startActivityForResult(intent, requestCode);
 * </pre>
 * 
 * To get the result of what you have selected, please in our
 * {@code onActivityResult(int, int, Intent)} method, received the result like
 * the follow code.
 * 
 * <pre>
 * String path = data.getStringExtra(FileFolderSelecterActivity.EXTRA_FOLDER);
 * </pre>
 * @author <a href="http://jileniao.net">Will.Zhang</a>
 */
public class FileFolderSelecterActivity extends Activity implements
        OnClickListener {

    private static final String ROOT = Environment
            .getExternalStorageDirectory().toString();
    private final int SELECTED_COLOR = Color.BLUE;

    public static final String SELECT_TYPE = "type";
    public static final String FILE_EXTENSION = "extension";
    public static final String RESULT = "result";

    private int mSelectType = 0;
    public static final int SELECT_TYPE_FOLDER = 0;
    public static final int SELECT_TYPE_FILE = 1;

    private String mFileExtension = "";
    private ListView mFilesLv;
    private TextView mCurrentTv;

    private FileLvAdapter mFileLvAdapter;
    private String mCurrentPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_select_folder);

        Intent intent = getIntent();
        if (intent != null) {
            mSelectType = intent.getIntExtra(SELECT_TYPE, SELECT_TYPE_FOLDER);
            if (mSelectType == SELECT_TYPE_FILE) {
                String extension = intent.getStringExtra(FILE_EXTENSION);
                if (extension != null) {
                    mFileExtension = extension;
                }
            }
        }

        mFilesLv = (ListView) findViewById(R.id.folder_lv);
        mCurrentTv = (TextView) findViewById(R.id.current_tv);
        findViewById(R.id.cancel_btn).setOnClickListener(this);
        findViewById(R.id.ok_btn).setOnClickListener(this);

        setCurrentPath(ROOT);
        mFileLvAdapter = new FileLvAdapter();
        setListAdapterData();
        mFilesLv.setAdapter(mFileLvAdapter);
        mFilesLv.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                    int position, long id) {
                if (isRootPath(mFileLvAdapter.getItem(position)
                        .getAbsolutePath())
                        || mFileLvAdapter.getItem(position).isDirectory()) {
                    return false;
                }
                mFileLvAdapter.setSelectedIndex(position);
                return true;
            }
        });
        mFilesLv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                File f = mFileLvAdapter.getItem(position);
                if (f.isDirectory()) {
                    setCurrentPath(mFileLvAdapter.getItem(position)
                            .getAbsolutePath());
                    setListAdapterData();
                    mFileLvAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void setCurrentPath(String path) {
        this.mCurrentPath = path;
        mCurrentTv.setText(path);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void setListAdapterData() {
        List<File> list = new ArrayList<File>();

        File topFile = new File(mCurrentPath);
        File[] files = topFile.listFiles();
        if (files == null) {
            Toast.makeText(this, "no files found!", Toast.LENGTH_SHORT).show();
            setResult(RESULT_CANCELED);
            this.finish();
            return;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                list.add(file);
            } else {
                if (mSelectType == SELECT_TYPE_FILE
                        && file.getAbsolutePath().endsWith(mFileExtension)) {
                    list.add(file);
                }
            }
        }

        Collections.sort(list, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if (o1.isDirectory() && o2.isFile()) {
                    // folder is before of file
                    return -1;
                }
                if (o1.isFile() && o2.isDirectory()) {
                    // file is behind of folder
                    return 1;
                }
                // sort by the ASCII code:a-z 0-9
                return -(o2.getName().toLowerCase().compareTo(o1.getName()
                        .toLowerCase()));
            }
        });

        if (!isRootPath(mCurrentPath)) {
            // if the current path is not ROOT_PATH, add ../ at the first
            list.add(0, new File(mCurrentPath).getParentFile());
        }
        mFileLvAdapter.setList(list);
        mFileLvAdapter.setSelectedIndex(-1);
    }

    private boolean isRootPath(String path) {
        return ROOT.equals(path);
    }

    private class FileLvAdapter extends BaseAdapter {

        private int mSelectedIndex = -1;
        public List<File> list;

        public void setList(List<File> l) {
            list = l;
        }

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public File getItem(int position) {
            return list.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) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(
                        FileFolderSelecterActivity.this).inflate(
                        R.layout.folder_list_item, null);
                holder.mIcon = (ImageView) convertView.findViewById(R.id.icon);
                holder.mText = (TextView) convertView.findViewById(R.id.text);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.mIcon
                    .setBackgroundResource(getItem(position).isFile() ? R.drawable.ic_file
                            : R.drawable.ic_folder);
            holder.mText
                    .setText(!isRootPath(mCurrentPath) && position == 0 ? "../"
                            : getItem(position).getName());

            if (position == mSelectedIndex) {
                convertView.setBackgroundColor(SELECTED_COLOR);
            } else {
                convertView.setBackgroundColor(Color.TRANSPARENT);
            }
            return convertView;
        }

        public void setSelectedIndex(int index) {
            mSelectedIndex = index;
            notifyDataSetChanged();
        }

        public int getSelectedIndex() {
            return mSelectedIndex;
        }

        class ViewHolder {
            public ImageView mIcon;
            public TextView mText;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.ok_btn:
            Intent intent = new Intent();
            intent.putExtra(RESULT,
                    mFileLvAdapter.getItem(mFileLvAdapter.getSelectedIndex())
                            .getAbsolutePath());
            setResult(RESULT_OK, intent);
            finish();
            break;
        case R.id.cancel_btn:
            setResult(RESULT_CANCELED);
            finish();
            break;

        default:
            break;
        }
    }
}


文末。。。
分享本文至:

WRITTEN BY

avatar
本文标签:androidfilefolder
看了本文是不是觉得很赞,那就赶紧点击下面按钮分享给身边的朋友吧!

2 条评论

  1. avatar 上海app开发

    学习 感谢分享

欢迎留言




用户登录

sitemap