1.对话框布局文件
注释部分为预留,如果是OpenFileDialog,在此处加入TextView用来显示当前目录,如果是SaveFileDialog,加入EditView用来输入要保存的文件名。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="40dip">
<Button android:layout_width="40dip"
android:layout_height="40dip"
android:id="@+id/FileChooserHomeBtn"
android:text="Home"
android:layout_weight="1"/>
<LinearLayout android:layout_width="140dip"
android:layout_height="35dip"
android:id="@+id/FileChooserDirLayout"
android:gravity="center"
android:layout_weight="1">
<!-- <TextView android:layout_width="140dip"
android:layout_height="35dip"
android:id="@+id/dir_str"
android:gravity="center"
android:layout_weight="1"/> -->
</LinearLayout>
<Button android:layout_width="40dip"
android:layout_height="40dip"
android:id="@+id/FileChooserBackBtn"
android:text="Back"
android:layout_weight="1"/>
</LinearLayout>
<ListView android:layout_width="fill_parent"
android:layout_height="300dip"
android:id="@+id/FileChooserDirList"/>
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/FileChooserOkBtn"
android:text="OK"/>
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/FileChooserCancelBtn"
android:text="Cancel"/>
</LinearLayout>
2.Dialog的java文件
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
/**
*
*
*
* @author
*
*/
public class FileOpenerDialog extends Dialog implements android.view.View.OnClickListener {
private android.widget.ListView list;
ArrayAdapter<String> Adapter;
ArrayList<String> arr = new ArrayList<String>();
Context context;
private String path;
private android.widget.TextView curFilePath;
private android.widget.EditText saveFileName;
private android.widget.Button home, back, ok, cancel;
private android.widget.LinearLayout layout;
private int type = 1;
private String[] fileType = null;
public final static int TypeOpen = 1;
public final static int TypeSave = 2;
private MyDialogListener listener;
/**
* @param context
* @param 值为1表示OpenFileDialog, 值为2表示SaveFileDialog
* @param 需要过滤的文件类型,若为空表示只显示文件夹
* @param 初始路径,这个有问题
*/
public FileOpenerDialog(Context context, int type, String[] fileType, String resultPath,
MyDialogListener listener) {
super(context);
// TODO Auto-generated constructor stub
this.context = context;
this.type = type;
this.fileType = fileType;
this.path = resultPath;
this.listener = listener;
}
@Override
public void dismiss() {
// TODO Auto-generated method stub
super.dismiss();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_filechooser);
path = getSDPath();
arr = (ArrayList<String>)getDirs(path);
Adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, arr);
list = (android.widget.ListView)findViewById(R.id.FileChooserDirList);
list.setAdapter(Adapter);
list.setOnItemClickListener(lvLis);
home = (android.widget.Button)findViewById(R.id.FileChooserHomeBtn);
home.setOnClickListener(this);
back = (android.widget.Button)findViewById(R.id.FileChooserBackBtn);
back.setOnClickListener(this);
ok = (android.widget.Button)findViewById(R.id.FileChooserOkBtn);
ok.setOnClickListener(this);
cancel = (android.widget.Button)findViewById(R.id.FileChooserCancelBtn);
cancel.setOnClickListener(this);
layout = (android.widget.LinearLayout)findViewById(R.id.FileChooserDirLayout);
if(type == TypeOpen)
{
// 若为OpenFileDialog,在预留的位置添加TextView,显示当前路径
curFilePath = new android.widget.TextView(context);
layout.addView(curFilePath);
curFilePath.setText(path);
}
else if(type == TypeSave)
{
// 若为SaveFileDialog,在预留的位置添加EditText,输入要保存的文件名
saveFileName = new android.widget.EditText(context);
saveFileName.setWidth(240);
saveFileName.setHeight(70);
saveFileName.setGravity(Gravity.CENTER);
saveFileName.setPadding(0, 2, 0, 0);
layout.addView(saveFileName);
saveFileName.setText("Enter file name");
}
}
// 自动更新ListView内容
Runnable add = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
arr.clear();
List<String> temp = getDirs(path);
for(int i = 0; i < temp.size(); i++) arr.add(temp.get(i));
Adapter.notifyDataSetChanged();
}
};
// 事件监听,当点击ListView的某个项目时触发
private OnItemClickListener lvLis = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String temp = (String)arg0.getItemAtPosition(arg2);
if(temp.equals("..")) path = getSubDir(path); // 如果点击的项目是"..",表示没有子目录,返回上一级目录
else if(path.equals("/")) path = path + temp; // 如果当前目录为根目录,直接添加子目录,例 "/" -> "/sdcard"
else path = path + "/" + temp; // 将子目录追加到当前目录后,例 "/sdcard" -> "/sdcard/xml"
if(type == TypeOpen) curFilePath.setText(path);
Handler handler = new Handler();
handler.post(add); // 因为当前目录改变,更新子文件夹
}
};
/**
* Get sub directories
* @param ipath
* @return
*/
private List<String> getDirs(String ipath) {
List<String> dirs = new ArrayList<String>();
File[] files = new File(ipath).listFiles();
if(files != null)
{
for(File f: files)
{
if(f.isDirectory())
{
String tmp = f.toString();
if(tmp.endsWith("/")) tmp = tmp.substring(0, tmp.length() - 1);
int pos = tmp.lastIndexOf("/");
dirs.add(tmp.substring(pos + 1, tmp.length()));
}
else if(f.isFile() && fileType != null)
{
for(int i = 0; i< fileType.length; i++)
{
int typeStrLen = fileType[i].length();
String fileName = f.getPath().substring(f.getPath().length() - typeStrLen);
if (fileName.equalsIgnoreCase(fileType[i]))
dirs.add(f.toString().substring(path.length() + 1, f.toString().length()));
}
}
}
}
if(dirs.size() == 0) dirs.add("..");
return dirs;
}
@Override
public void onClick(View args0) {
// TODO Auto-generated method stub
if(args0.getId() == home.getId())
{
// 点击"Home"按钮,回到根目录
path = getRootDir();
if(type == TypeOpen) curFilePath.setText(path);
Handler handler = new Handler();
handler.post(add); // 更新子文件夹
}
else if(args0.getId() == back.getId())
{
// 点击"Back"按钮,返回上一级文件夹
path = getSubDir(path);
if(type == TypeOpen) curFilePath.setText(path);
Handler handler = new Handler();
handler.post(add); // 更新子文件夹
}
else if(args0.getId() == ok.getId())
{
// 点击"OK"按钮,关闭对话框,调用自定义监视器的OnOKClick方法,将当前目录返回主Activity
dismiss();
listener.OnOkClick(path);
}
else if(args0.getId() == cancel.getId())
{
// 点击"Cancel”按钮
this.cancel();
}
}
/**
* Get SD card directory, if SD card not exist, return '/'
* @return
*/
private String getSDPath() {
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED); // 判断是否存在SD卡
if(sdCardExist)
{
sdDir = Environment.getExternalStorageDirectory(); // 如果SD卡存在,返回SD卡的目录
}
if(sdDir == null)
{
return "/"; // 如果SD卡不存在,返回根目录
}
return sdDir.toString();
}
private String getRootDir() {
return "/";
}
/**
* Get upper directory
* @param path
* @return
*/
private String getSubDir(String path) {
String subpath = "/";
if(path.endsWith("/"))
{
path = path.substring(0, path.length() - 1);
}
int pos = path.lastIndexOf("/");
if(pos > 0)
{
subpath = path.substring(0, pos);
}
return subpath;
}
}
3.自定义监视器接口,用以获取对话框的返回值
主Activity中实现接口,将接口实例作为对话框构造函数的参数传入。
当点击对话框的OK按钮时,调用接口实例的 OnOkClick (String path) 方法,将对话框的返回值作为参数传入。
主Activity的实现函数中,将参数作为对话框的返回值处理。
public interface MyDialogListener {
public void OnOkClick (String result);
}
4.主Activity的Java文件,只有相关部分
public class PrinterUtilityActivity extends Activity implements MyDialogListener {
private TextView xmlpath;
@Override
public void OnOkClick(String path) {
// 将对话框返回值显示在TextView中
xmlpath = (TextView)this.findViewById(R.id.UtilitySelectDirectoryText);
xmlpath.setText(path);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.printer_utility_layout);
// 添加按钮的监听事件,点击按钮时弹出对话框
Button openDirBtn = (Button)this.findViewById(R.id.UtilitySelectDirectoryBtn);
openDirBtn.setOnClickListener(new OnClickListener () {
@Override
public void onClick(View args0) {
String path = null;
FileOpenerDialog dlg = new FileOpenerDialog(PrinterUtilityActivity.this, 1, null, path, PrinterUtilityActivity.this);
dlg.setTitle("Choose xml folder");
dlg.show();
}
});
... ...
}
}