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();
- }
- <span style="white-space:pre"> </span>};
-
- <span style="white-space:pre"> </span> // 事件監聽,當點擊ListView的某個項目時觸發
- <span style="white-space:pre"> </span> 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();
- <span style="white-space:pre"> </span> handler.post(add);<span style="white-space:pre"> </span>// 因為當前目錄改變,更新子文件夾
- }
- <span style="white-space:pre"> </span> };
-
- <span style="white-space:pre"> </span> /**
- <span > </span> * Get sub directories
- <span > </span> * @param ipath
- <span > </span> * @return
- <span > </span> */
- <span style="white-space:pre"> </span> 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();
- <span style="white-space:pre"> </span>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();
- }
- });
-
- ... ...
- }
- }