カテゴリー
SugiBlog Webデザイナー・プログラマーのためのお役立ちTips

フォルダ選択ダイアログ

この記事は最終更新日から1年以上経過しています。

アラートダイアログを使って、ファイル選択にも応用できる参照機能
こちらのサイトを参考にさせていただきました。
http://d.hatena.ne.jp/Silent-Bob/20110705

・ルートフォルダーを設定
指定したフォルダー階層より上に上がれないようにします。

private static final String ROOT_PATH = 
    Environment.getExternalStorageDirectory().getPath() + "/";


再帰的に利用するため、ダイアログ表示をメソッドとして定義

private void SelectDirectoryDialog(final Context context, final String parentPath) {
    AlertDialog.Builder ad = new AlertDialog.Builder(context);
    ad.setTitle(parentPath);
    ad.setCancelable(false);

    ad.setNegativeButton("キャンセル", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int whichButton) {
          return;
        }
    });

    try{
        File[] files = new File(parentPath).listFiles();

        ArrayList<String> pathList = new ArrayList<String>();
        for (File file : files) {
            if(file.isDirectory()){
                //ディレクトリの場合
                pathList.add(file.getName());
            }
        }

        Collections.sort(pathList);//ソート
        pathList.add(0, "このフォルダを選択する");
        pathList.add(1, "一つ前に戻る");

        //配列に変換
        final String[] items = pathList.toArray(new String[0]);

        ad.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch(which){
                case 0:
                    TextView tv = (TextView)findViewById(R.id.textView1);
                    tv.setText(parentPath);
                    break;

                case 1:
                    if(parentPath.equals(ROOT_PATH)){
                        Toast.makeText(context, "これ以上戻れません", Toast.LENGTH_SHORT).show();
                        SelectDirectoryDialog(context, parentPath);
                    }else{
                        //parentの一つ前のパスを取得
                        String grandparentPath = parentPath.substring(0, parentPath.length()-1);
                        grandparentPath = grandparentPath.substring(0, grandparentPath.lastIndexOf("/")+1);
                        SelectDirectoryDialog(context, grandparentPath);
                    }
                    break;

                default:
                    SelectDirectoryDialog(context, parentPath + items[which] + "/");
                    break;
                }
            }
        });
    }catch(Exception e){
        e.printStackTrace();
    }
    ad.create().show();
}

ファイルも選択できるようにしました。

private void SelectDirectoryDialog(final Context context, final String parentPath){
    TextView tv;
    AlertDialog.Builder ad = new AlertDialog.Builder(context);
    ad.setTitle(parentPath);
    ad.setCancelable(false);
    ad.setNegativeButton("キャンセル", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int whichButton) {
        return;
    }

    });
    try{
        //ファイル名のフィルターを作成
        FilenameFilter fFilter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                boolean f;
                if(new File(dir + "/" + filename).isDirectory()) {
                    f = true;
                } else if (filename.matches(".+.jpg")) { //正規表現で検索
                    f = true;
                } else {
                    f = false;
                }
                return f;
            }
        };

        File[] files = new File(parentPath).listFiles(fFilter);

        ArrayList<String> pathList = new ArrayList<String>();
        for (File file : files) {
            pathList.add(file.getName());
    }

    Collections.sort(pathList);//ソート
    pathList.add(0, "このフォルダを選択する");
    pathList.add(1, "一つ前に戻る");

    //配列に変換
    final String[] items = pathList.toArray(new String[0]);

    ad.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch(which){
                case 0:
                    tv = (TextView)findViewById(R.id.textView1);
                    tv.setText(parentPath);
                    break;
                case 1:
                    if(parentPath.equals(ROOT_PATH)){
                        Toast.makeText(context, "これ以上戻れません", Toast.LENGTH_SHORT).show();
                        SelectDirectoryDialog(context, parentPath);
                    }else{
                        //parentの一つ前のパスを取得
                        String grandparentPath = parentPath.substring(0, parentPath.length()-1);
                        grandparentPath = grandparentPath.substring(0, grandparentPath.lastIndexOf("/")+1);
                        SelectDirectoryDialog(context, grandparentPath);
                    }
                    break;
                default:
                    File f = new File(parentPath + items[which]);
                    if(f.isFile()) {
                        tv = (TextView)findViewById(R.id.textView1);
                        tv.setText(parentPath + items[which]);
                    } else {
                        SelectDirectoryDialog(context, parentPath + items[which] + "/");
                    }
                    break;
            }
        }
    });
    }catch(Exception e){
        e.printStackTrace();
    }
    ad.create().show();
}

この記事に対して、「Android(Java)初心者です。onOptionsItemSelectedからダイアログを表示するにはどのような記述が必要でしょうか?」という質問があったようなので追記しました。2013-06-12
http://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q1081951280

使用例1)Activityを継承したpublicクラスのメソッド内で実行する場合

SelectDirectoryDialog(this, ROOT_PATH);

第2引数「parentPath」に最初に表示させたいフォルダーを指定します。
ここではルートフォルダーを指定しています。

使用例2)メニューを選択した場合に実行

public boolean onOptionsItemSelected(MenuItem item){
  switch(item.getItemId()){
  case R.id.item01:
    SelectDirectoryDialog(this, ROOT_PATH);
    return true;
  default:
    return super.onOptionsItemSelected(item);
  }
}

メニューについてはこちらに書いています。
[メニューを設定する]
FilenameFilterについてはこちら
[FilenameFilter]

この記事がお役に立ちましたらシェアお願いします
10,457 views

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です