android打开文件、保存对话框、创建新文件夹对话框(转载)

转载地址:点击打开

这是一个简单的只有3个按钮的程序,3个按钮分别对应三种工作的模式(保存、打开和文件夹选择)。封装的SimpleFileDialog.java的内容如下:

package com.example.test;

/*
 *
 * This file is licensed under The Code Project Open License (CPOL) 1.02
 * http://www.codeproject.com/info/cpol10.aspx
 * http://www.codeproject.com/info/CPOL.zip
 *
 * License Preamble:
 * This License governs Your use of the Work. This License is intended to allow developers to use the Source
 * Code and Executable Files provided as part of the Work in any application in any form.
 *
 * The main points subject to the terms of the License are:
 *    Source Code and Executable Files can be used in commercial applications;
 *    Source Code and Executable Files can be redistributed; and
 *    Source Code can be modified to create derivative works.
 *    No claim of suitability, guarantee, or any warranty whatsoever is provided. The software is provided "as-is".
 *    The Article(s) accompanying the Work may not be distributed or republished without the Author‘s consent
 *
 * This License is entered between You, the individual or other entity reading or otherwise making use of
 * the Work licensed pursuant to this License and the individual or other entity which offers the Work
 * under the terms of this License ("Author").
 *  (See Links above for full license text)
 */

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
//import android.content.DialogInterface.OnKeyListener;
import android.os.Environment;
import android.text.Editable;
import android.view.Gravity;
//import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SimpleFileDialog {
    private int FileOpen = 0;
    private int FileSave = 1;
    private int FolderChoose = 2;
    private int Select_type = FileSave;
    private String m_sdcardDirectory = "";
    private Context m_context;
    private TextView m_titleView1;
    private TextView m_titleView;
    public String Default_File_Name = "default.txt";
    private String Selected_File_Name = Default_File_Name;
    private EditText input_text;

    private String m_dir = "";
    private List<String> m_subdirs = null;
    private SimpleFileDialogListener m_SimpleFileDialogListener = null;
    private ArrayAdapter<String> m_listAdapter = null;

    // ////////////////////////////////////////////////////
    // Callback interface for selected directory
    // ////////////////////////////////////////////////////
    public interface SimpleFileDialogListener {
        public void onChosenDir(String chosenDir);
    }

    public SimpleFileDialog(Context context, String file_select_type,
            SimpleFileDialogListener SimpleFileDialogListener) {
        if (file_select_type.equals("FileOpen"))
            Select_type = FileOpen;
        else if (file_select_type.equals("FileSave"))
            Select_type = FileSave;
        else if (file_select_type.equals("FolderChoose"))
            Select_type = FolderChoose;
        else
            Select_type = FileOpen;

        m_context = context;
        m_sdcardDirectory = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        m_SimpleFileDialogListener = SimpleFileDialogListener;

        try {
            m_sdcardDirectory = new File(m_sdcardDirectory).getCanonicalPath();
        } catch (IOException ioe) {
        }
    }

    // /////////////////////////////////////////////////////////////////////
    // chooseFile_or_Dir() - load directory chooser dialog for initial
    // default sdcard directory
    // /////////////////////////////////////////////////////////////////////
    public void chooseFile_or_Dir() {
        // Initial directory is sdcard directory
        if (m_dir.equals(""))
            chooseFile_or_Dir(m_sdcardDirectory);
        else
            chooseFile_or_Dir(m_dir);
    }

    // //////////////////////////////////////////////////////////////////////////////
    // chooseFile_or_Dir(String dir) - load directory chooser dialog for initial
    // input ‘dir‘ directory
    // //////////////////////////////////////////////////////////////////////////////
    public void chooseFile_or_Dir(String dir) {
        File dirFile = new File(dir);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            dir = m_sdcardDirectory;
        }

        try {
            dir = new File(dir).getCanonicalPath();
        } catch (IOException ioe) {
            return;
        }

        m_dir = dir;
        m_subdirs = getDirectories(dir);

        class SimpleFileDialogOnClickListener implements
                DialogInterface.OnClickListener {
            public void onClick(DialogInterface dialog, int item) {
                String m_dir_old = m_dir;
                String sel = ""
                        + ((AlertDialog) dialog).getListView().getAdapter()
                                .getItem(item);
                if (sel.charAt(sel.length() - 1) == ‘/‘)
                    sel = sel.substring(0, sel.length() - 1);

                // Navigate into the sub-directory
                if (sel.equals("..")) {
                    m_dir = m_dir.substring(0, m_dir.lastIndexOf("/"));
                } else {
                    m_dir += "/" + sel;
                }
                Selected_File_Name = Default_File_Name;

                if ((new File(m_dir).isFile())) // If the selection is a regular
                                                // file
                {
                    m_dir = m_dir_old;
                    Selected_File_Name = sel;
                }

                updateDirectory();
            }
        }

        AlertDialog.Builder dialogBuilder = createDirectoryChooserDialog(dir,
                m_subdirs, new SimpleFileDialogOnClickListener());

        dialogBuilder.setPositiveButton("OK", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Current directory chosen
                // Call registered listener supplied with the chosen directory
                if (m_SimpleFileDialogListener != null) {
                    {
                        if (Select_type == FileOpen || Select_type == FileSave) {
                            Selected_File_Name = input_text.getText() + "";
                            m_SimpleFileDialogListener.onChosenDir(m_dir + "/"
                                    + Selected_File_Name);
                        } else {
                            m_SimpleFileDialogListener.onChosenDir(m_dir);
                        }
                    }
                }
            }
        }).setNegativeButton("Cancel", null);

        final AlertDialog dirsDialog = dialogBuilder.create();

        // Show directory chooser dialog
        dirsDialog.show();
    }

    private boolean createSubDir(String newDir) {
        File newDirFile = new File(newDir);
        if (!newDirFile.exists())
            return newDirFile.mkdir();
        else
            return false;
    }

    private List<String> getDirectories(String dir) {
        List<String> dirs = new ArrayList<String>();
        try {
            File dirFile = new File(dir);

            // if directory is not the base sd card directory add ".." for going
            // up one directory
            if (!m_dir.equals(m_sdcardDirectory))
                dirs.add("..");

            if (!dirFile.exists() || !dirFile.isDirectory()) {
                return dirs;
            }

            for (File file : dirFile.listFiles()) {
                if (file.isDirectory()) {
                    // Add "/" to directory names to identify them in the list
                    dirs.add(file.getName() + "/");
                } else if (Select_type == FileSave || Select_type == FileOpen) {
                    // Add file names to the list if we are doing a file save or
                    // file open operation
                    dirs.add(file.getName());
                }
            }
        } catch (Exception e) {
        }

        Collections.sort(dirs, new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        return dirs;
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////
    // //// START DIALOG DEFINITION //////
    // ////////////////////////////////////////////////////////////////////////////////////////////////////////
    private AlertDialog.Builder createDirectoryChooserDialog(String title,
            List<String> listItems,
            DialogInterface.OnClickListener onClickListener) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(m_context);
        // //////////////////////////////////////////////
        // Create title text showing file select type //
        // //////////////////////////////////////////////
        m_titleView1 = new TextView(m_context);
        m_titleView1.setLayoutParams(new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        // m_titleView1.setTextAppearance(m_context,
        // android.R.style.TextAppearance_Large);
        // m_titleView1.setTextColor(
        // m_context.getResources().getColor(android.R.color.black) );

        if (Select_type == FileOpen)
            m_titleView1.setText("Open:");
        if (Select_type == FileSave)
            m_titleView1.setText("Save As:");
        if (Select_type == FolderChoose)
            m_titleView1.setText("Folder Select:");

        // need to make this a variable Save as, Open, Select Directory
        m_titleView1.setGravity(Gravity.CENTER_VERTICAL);
        m_titleView1.setBackgroundColor(-12303292); // dark gray -12303292
        m_titleView1.setTextColor(m_context.getResources().getColor(
                android.R.color.white));

        // Create custom view for AlertDialog title
        LinearLayout titleLayout1 = new LinearLayout(m_context);
        titleLayout1.setOrientation(LinearLayout.VERTICAL);
        titleLayout1.addView(m_titleView1);

        if (Select_type == FolderChoose || Select_type == FileSave) {
            // /////////////////////////////
            // Create New Folder Button //
            // /////////////////////////////
            Button newDirButton = new Button(m_context);
            newDirButton.setLayoutParams(new LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            newDirButton.setText("New Folder");
            newDirButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final EditText input = new EditText(m_context);

                    // Show new folder name input dialog
                    new AlertDialog.Builder(m_context)
                            .setTitle("New Folder Name")
                            .setView(input)
                            .setPositiveButton("OK",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog,
                                                int whichButton) {
                                            Editable newDir = input.getText();
                                            String newDirName = newDir
                                                    .toString();
                                            // Create new directory
                                            if (createSubDir(m_dir + "/"
                                                    + newDirName)) {
                                                // Navigate into the new
                                                // directory
                                                m_dir += "/" + newDirName;
                                                updateDirectory();
                                            } else {
                                                Toast.makeText(
                                                        m_context,
                                                        "Failed to create ‘"
                                                                + newDirName
                                                                + "‘ folder",
                                                        Toast.LENGTH_SHORT)
                                                        .show();
                                            }
                                        }
                                    }).setNegativeButton("Cancel", null).show();
                }
            });
            titleLayout1.addView(newDirButton);
        }

        // ///////////////////////////////////////////////////
        // Create View with folder path and entry text box //
        // ///////////////////////////////////////////////////
        LinearLayout titleLayout = new LinearLayout(m_context);
        titleLayout.setOrientation(LinearLayout.VERTICAL);

        m_titleView = new TextView(m_context);
        m_titleView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
        m_titleView.setBackgroundColor(-12303292); // dark gray -12303292
        m_titleView.setTextColor(m_context.getResources().getColor(
                android.R.color.white));
        m_titleView.setGravity(Gravity.CENTER_VERTICAL);
        m_titleView.setText(title);

        titleLayout.addView(m_titleView);

        if (Select_type == FileOpen || Select_type == FileSave) {
            input_text = new EditText(m_context);
            input_text.setText(Default_File_Name);
            titleLayout.addView(input_text);
        }
        // ////////////////////////////////////////
        // Set Views and Finish Dialog builder //
        // ////////////////////////////////////////
        dialogBuilder.setView(titleLayout);
        dialogBuilder.setCustomTitle(titleLayout1);
        m_listAdapter = createListAdapter(listItems);
        dialogBuilder.setSingleChoiceItems(m_listAdapter, -1, onClickListener);
        dialogBuilder.setCancelable(false);
        return dialogBuilder;
    }

    private void updateDirectory() {
        m_subdirs.clear();
        m_subdirs.addAll(getDirectories(m_dir));
        m_titleView.setText(m_dir);
        m_listAdapter.notifyDataSetChanged();
        // #scorch
        if (Select_type == FileSave || Select_type == FileOpen) {
            input_text.setText(Selected_File_Name);
        }
    }

    private ArrayAdapter<String> createListAdapter(List<String> items) {
        return new ArrayAdapter<String>(m_context,
                android.R.layout.select_dialog_item, android.R.id.text1, items) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View v = super.getView(position, convertView, parent);
                if (v instanceof TextView) {
                    // Enable list item (directory) text wrapping
                    TextView tv = (TextView) v;
                    tv.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
                    tv.setEllipsize(null);
                }
                return v;
            }
        };
    }
}

MainActivity.java:

package com.example.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

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

        //Button1
        Button dirChooserButton1 = (Button) findViewById(R.id.button1);
        dirChooserButton1.setOnClickListener(new OnClickListener()
        {
            String m_chosen;
            @Override
            public void onClick(View v) {
                /////////////////////////////////////////////////////////////////////////////////////////////////
                //Create FileOpenDialog and register a callback
                /////////////////////////////////////////////////////////////////////////////////////////////////
                SimpleFileDialog FileOpenDialog =  new SimpleFileDialog(MainActivity.this, "FileOpen",
                        new SimpleFileDialog.SimpleFileDialogListener()
                {
                    @Override
                    public void onChosenDir(String chosenDir)
                    {
                        // The code in this function will be executed when the dialog OK button is pushed
                        m_chosen = chosenDir;
                        Toast.makeText(MainActivity.this, "Chosen FileOpenDialog File: " +
                                m_chosen, Toast.LENGTH_LONG).show();
                    }
                });

                //You can change the default filename using the public variable "Default_File_Name"
                FileOpenDialog.Default_File_Name = "";
                FileOpenDialog.chooseFile_or_Dir();

                /////////////////////////////////////////////////////////////////////////////////////////////////

            }
        });

        //Button2
        Button dirChooserButton2 = (Button) findViewById(R.id.button2);
        dirChooserButton2.setOnClickListener(new OnClickListener()
        {
            String m_chosen;
            @Override
            public void onClick(View v) {
                /////////////////////////////////////////////////////////////////////////////////////////////////
                //Create FileSaveDialog and register a callback
                /////////////////////////////////////////////////////////////////////////////////////////////////
                SimpleFileDialog FileSaveDialog =  new SimpleFileDialog(MainActivity.this, "FileSave",
                        new SimpleFileDialog.SimpleFileDialogListener()
                {
                    @Override
                    public void onChosenDir(String chosenDir)
                    {
                        // The code in this function will be executed when the dialog OK button is pushed
                        m_chosen = chosenDir;
                        Toast.makeText(MainActivity.this, "Chosen FileOpenDialog File: " +
                                m_chosen, Toast.LENGTH_LONG).show();
                    }
                });

                //You can change the default filename using the public variable "Default_File_Name"
                FileSaveDialog.Default_File_Name = "my_default.txt";
                FileSaveDialog.chooseFile_or_Dir();

                /////////////////////////////////////////////////////////////////////////////////////////////////

            }
        });

        //Button3
        Button dirChooserButton3 = (Button) findViewById(R.id.button3);
        dirChooserButton3.setOnClickListener(new OnClickListener()
        {
            String m_chosen;
            @Override
            public void onClick(View v) {

                /////////////////////////////////////////////////////////////////////////////////////////////////
                //Create FileOpenDialog and register a callback
                /////////////////////////////////////////////////////////////////////////////////////////////////
                SimpleFileDialog FolderChooseDialog =  new SimpleFileDialog(MainActivity.this, "FolderChoose",
                        new SimpleFileDialog.SimpleFileDialogListener()
                {
                    @Override
                    public void onChosenDir(String chosenDir)
                    {
                        // The code in this function will be executed when the dialog OK button is pushed
                        m_chosen = chosenDir;
                        Toast.makeText(MainActivity.this, "Chosen FileOpenDialog File: " +
                                m_chosen, Toast.LENGTH_LONG).show();
                    }
                });

                FolderChooseDialog.chooseFile_or_Dir();

                /////////////////////////////////////////////////////////////////////////////////////////////////

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

当然需要相应的权限:

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

最后来几张图片:

时间: 2024-10-04 22:05:11

android打开文件、保存对话框、创建新文件夹对话框(转载)的相关文章

更新文件时间戳或创建新文件命令

更新文件时间戳或创建新文件 touch 文件有三个主要变动时间: modification time (mtime): 当文件内容数据被改变时,更新时间 status time (ctime): 当文件权限和属性被改变时,更新时间 access time (atime): 当文件被访问时,更新时间 touch [-acdmt] 文件 参数: -a: 仅修改访问时间 -c: 仅修改文件的时间,若该文件不存在则不创建新文件 -d: --date=日期和时间 指定要设定的修改日期时间 -m: 仅修改m

sublime text 3创建新文件插件-AdvanceNewFile

这里要记录sublime text 3 在创建新文件时安装的插件–AdvanceNewFile ST本来自带的创建新文件的快捷键是ctrl+n.但是用户需要保存时才可修改名称以及文件路径.但是安装完AdvanceNewFile插件后,一切都会变得相当容易. 依旧在 package control 中选择 package control install.然后输入AdvanceNewFile,点击安装.知道出现如下界面,证明安装完成. 测试: 按着ctrl+alt+n ,下方会出现一个填写路径的框,

Android 打开/播放电脑的音频/视频文件

今天早上一到办公室,照常打开博客园看文章,看到有一片文章是用  http://www.cnblogs.com/wdfrog/p/3738180.html 看到这哥们实现的方法好复杂,又是配置电脑端,又是配置手机端,还又是转码啥的,倒腾时间长不说,而且还很麻烦,这里介绍下我是如何用手机直接播放电脑上的文件的. 之所以播放电脑上的文件,主要原因是视频文件都很大,清晰度高的一部电影都1GB左右了,对于手机来说,虽然能够装得下,但是看完就得删了,没法长时间储存在手机上, 来回往手机上拷视频文件,就这文件

NFS(expirtfs命令,NFS客户端创建新文件所属组和所属主都为nobody)

一.exportfs命令 nfs进程不能随便从新启动,如果不得已要重启,必须把客户端的挂载目录卸载,然后在从新启动. 这时候就可以用exportfs命令 -a             全部挂载或者全部卸载 -r             重新挂载 -u             卸载某一个目录 -v             显示共享目录 实验: 我们在服务端的配置文件从新写一行配置 [[email protected] nfstestdir]# vim /etc/exports /tmp/ 192.

android 打开 res raw目录 中 数据库文件

韩梦飞沙  韩亚飞  [email protected]  yue31313  han_meng_fei_sha 安卓不能直接打开 res raw 中的 数据库 文件. 通过 资源 获取资源 方法 , 然后在通过 打开资产资源方法 获得 res raw中的  输入流  对象, 然后将 输入流对象 中的数据 写入 其他目录中的相应文件中. 然后 通过 sqlite数据库的 打开或者创建数据库方法  来打开任意目录中的 sqlite

[ATL/WTL]_[中级]_[保存CBitmap到文件-保存屏幕内容到文件]

场景: 1. 在做图片处理时,比方放大后或加特效后须要保存CBitmap(HBITMAP)到文件. 2.截取屏幕内容到文件时. 3.不须要增加第3方库时. 说明: 这段代码部分来自网上.第一次学atl/wtl.gdi不是非常熟悉.以后转换为wtl版本号吧. 当然wtl项目直接用也没问题. 如今想想wxWidgets的wxImage类对这类操作方便多了.仅仅须要调用一个SaveFile方法. 保存HBITMAP到文件: static bool SaveBitmapToFile(CBitmap& b

[ATL/WTL]_[保存CBitmap到文件-保存屏幕内容到文件]

场景: 1. 在做图片处理时,比如放大后或加特效后需要保存CBitmap(HBITMAP)到文件. 2.截取屏幕内容到文件时. 3.不需要加入第3方库时. 说明: 这段代码部分来自网上,第一次学atl/wtl,gdi不是很熟悉,以后转换为wtl版本吧.当然wtl项目直接用也没问题. 现在想想wxWidgets的wxImage类对这类操作方便多了.只需要调用一个SaveFile方法. 保存HBITMAP到文件: static bool SaveBitmapToFile(CBitmap& bitma

XML文件操作类--创建XML文件

这个类是在微软XML操作类库上进行的封装,只是为了更加简单使用,包括XML类创建节点的示例. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace testForm { class Operation_APPCFG { XmlDocument xmldoc; XmlNode

linux文件类型:设备文件、mknod创建设备文件

设备文件: 块设备文件b: 按块为单位,随机访问的设备: 字符设备文件c:按字符为单位,线性设备: 常见的块设备文件b: 硬盘 硬盘设备的设备文件名:    IDE ,ATA: hd    SATA.SCSI.USB:sd          a,b,c,...来区分同一类型下的不同设备 IDE: 第一个IDE口:主.从 /dev/hda, /dev/hdb 第二个IDE口:主.从 /dev/hdc, /dev/hdd SD:  sda, sdb, sdc,... hda: hda1: 第一个主分