转载地址:点击打开

这是一个简单的只有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"/>

最后来几张图片:

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

  1. inode引起的Linux无法创建新文件,磁盘空间不足

    df -h,判断硬盘空间是否已经满了,占用率达100% ,就可以断定该分区满了. df -ia,占用率达100%,也会导致无法创建新文件.一般都是存在大量小文件引起的. inode包含文件的元信息,具 ...

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

    这里要记录sublime text 3 在创建新文件时安装的插件–AdvanceNewFile ST本来自带的创建新文件的快捷键是ctrl+n.但是用户需要保存时才可修改名称以及文件路径.但是安装完A ...

  3. 《UNIX环境高级编程》笔记--文件访问权限和新文件、目录所有权

    1.与进程关联的用户ID和组ID 与一个进程关联的ID有一下几个: 实际用户ID和实际组ID标识我们究竟是谁.通常在一个会话间值是不会改变的,但是超级用户进程有方法改变 他们,在以后的进程控制中会进行 ...

  4. Dom4j解析Xml文件,Dom4j创建Xml文件

    Dom4j解析Xml文件,Dom4j创建Xml文件 >>>>>>>>>>>>>>>>>>&g ...

  5. 用cmd打开TXT(中文)文件,以及创建空文件,删除文件,改变输入法

    编码               十进制 ut-8                65001 GBK               936 美国英语        437 windows cmd 默认为 ...

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

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha 安卓不能直接打开 res raw 中的 数据库 文件. 通过 资源 获取资源 方法 , ...

  7. Itext读取PDF模板文件渲染数据后创建新文件

    Maven导入依赖 <properties> <itextpdf.version>5.5.0</itextpdf.version> <itext-asian. ...

  8. 根据http协议下载文件保存到相应的文件下

    本实例通过提供的http网址来下载文件,并保存到本地指定的文件下. 本例提供的网址为:http://112.53.80.131:8888/database/11.mdb,下载的文件名为:11.mdb ...

  9. 3.Git基础-查看当前文件状态、跟踪新文件、暂存文件、忽略文件、提交更新、移除文件、移动文件

    1.检查当前文件状态 --  git status  git diff  git diff --staged   git status :我们可以使用 git status 来查看文件所处的状态.当运 ...

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

    场景: 1. 在做图片处理时,比方放大后或加特效后须要保存CBitmap(HBITMAP)到文件. 2.截取屏幕内容到文件时. 3.不须要增加第3方库时. 说明: 这段代码部分来自网上.第一次学atl ...

随机推荐

  1. LAMP 1.9域名301跳转

    给两个域名分主次.输入次域名跳转到主域名然后进行访问. 首先打开虚拟机配置文件. vim /usr/local/apache2/conf/extra/httpd-vhosts.conf 把这段配置添加 ...

  2. source in sight 删除工程

    用十六进制编辑器打开  "我的文档/Source Insight/Projects/PROJECTS.DB3" 文件 ,找到你要删除的项目路径及名称字符串,用0替换相关位置的数据.

  3. Add lombok to IntelliJ IDEA

    Lombok study link: https://www.jianshu.com/p/365ea41b3573 Add below dependency code to pom.xml <d ...

  4. Flask14 渲染问题、API、项目文档

    3 前端渲染和后端渲染 这两种渲染都属于动态页面 区分前后端渲染的关键点是站在浏览器的角度 3.1 后端渲染 浏览器请求服务器后获取到的是完整的HTML页面(即:后台已经组装好HTML文件啦),利用f ...

  5. solr搜索应用

    非票商品搜索,为了不模糊查询影响数据库的性能,搭建了solr搜索应用,php从solr读取数据

  6. Sharepoint2013商务智能学习笔记之Excel Service展示Sql Server数据Demo(五)

    第一步,打开Excel新建空白工作簿 第二步,使用Excel连接sql 数据库 第三步,画图 第四步 添加筛选器 最后效果如下: 第五步,将Excel上传到sharepoint任意文档库,并直接点击 ...

  7. wxpython实现文件拖拽

    我想让wx.grid里面的单元格能够支持文件拖拽,实现起来挺简单的,共分3步: 1.创建一个wx.FileDropTarget子类的对象,并把要支持拖拽的控件传给它的构造函数,此处是grid 2.调用 ...

  8. PAT 1071【STL string应用】

    1.单case很多清空没必要的 2.string+ char 最好用pushback 3.string +string就直接+ #include <bits/stdc++.h> using ...

  9. go语言实战教程:实战项目资源导入和项目框架搭建

    从本节内容开始,我们将利用我们所学习的Iris框架的相关知识,进行实战项目开发. 实战项目框架搭建 我们的实战项目是使用Iris框架开发一个关于本地服务平台的后台管理平台.平台中可以管理用户.商品.商 ...

  10. uva 1615 高速公路(贪心,区间问题)

    uva 1615 高速公路(贪心,区间问题) 给定平面上n个点和一个值D,要求在x轴上选出尽量少的点,使得对于给定的每个点,都有一个选出的点离它的欧几里得距离不超过D.(n<=1e5) 对于每个 ...