歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android基礎教程:簡易的文件對話框

Android基礎教程:簡易的文件對話框

日期:2017/3/1 11:09:28   编辑:Linux編程
1.對話框布局文件

注釋部分為預留,如果是OpenFileDialog,在此處加入TextView用來顯示當前目錄,如果是SaveFileDialog,加入EditView用來輸入要保存的文件名。
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent">
  6. <LinearLayout android:orientation="horizontal"
  7. android:layout_width="fill_parent"
  8. android:layout_height="40dip">
  9. <Button android:layout_width="40dip"
  10. android:layout_height="40dip"
  11. android:id="@+id/FileChooserHomeBtn"
  12. android:text="Home"
  13. android:layout_weight="1"/>
  14. <LinearLayout android:layout_width="140dip"
  15. android:layout_height="35dip"
  16. android:id="@+id/FileChooserDirLayout"
  17. android:gravity="center"
  18. android:layout_weight="1">
  19. <!-- <TextView android:layout_width="140dip"
  20. android:layout_height="35dip"
  21. android:id="@+id/dir_str"
  22. android:gravity="center"
  23. android:layout_weight="1"/> -->
  24. </LinearLayout>
  25. <Button android:layout_width="40dip"
  26. android:layout_height="40dip"
  27. android:id="@+id/FileChooserBackBtn"
  28. android:text="Back"
  29. android:layout_weight="1"/>
  30. </LinearLayout>
  31. <ListView android:layout_width="fill_parent"
  32. android:layout_height="300dip"
  33. android:id="@+id/FileChooserDirList"/>
  34. <Button android:layout_width="fill_parent"
  35. android:layout_height="wrap_content"
  36. android:id="@+id/FileChooserOkBtn"
  37. android:text="OK"/>
  38. <Button android:layout_width="fill_parent"
  39. android:layout_height="wrap_content"
  40. android:id="@+id/FileChooserCancelBtn"
  41. android:text="Cancel"/>
  42. </LinearLayout>
2.Dialog的java文件
  1. import java.io.File;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import android.app.Dialog;
  5. import android.content.Context;
  6. import android.os.Bundle;
  7. import android.os.Environment;
  8. import android.os.Handler;
  9. import android.view.Gravity;
  10. import android.view.View;
  11. import android.widget.AdapterView;
  12. import android.widget.AdapterView.OnItemClickListener;
  13. import android.widget.ArrayAdapter;
  14. /**
  15. *
  16. *
  17. *
  18. * @author
  19. *
  20. */
  21. public class FileOpenerDialog extends Dialog implements android.view.View.OnClickListener {
  22. private android.widget.ListView list;
  23. ArrayAdapter<String> Adapter;
  24. ArrayList<String> arr = new ArrayList<String>();
  25. Context context;
  26. private String path;
  27. private android.widget.TextView curFilePath;
  28. private android.widget.EditText saveFileName;
  29. private android.widget.Button home, back, ok, cancel;
  30. private android.widget.LinearLayout layout;
  31. private int type = 1;
  32. private String[] fileType = null;
  33. public final static int TypeOpen = 1;
  34. public final static int TypeSave = 2;
  35. private MyDialogListener listener;
  36. /**
  37. * @param context
  38. * @param 值為1表示OpenFileDialog, 值為2表示SaveFileDialog
  39. * @param 需要過濾的文件類型,若為空表示只顯示文件夾
  40. * @param 初始路徑,這個有問題
  41. */
  42. public FileOpenerDialog(Context context, int type, String[] fileType, String resultPath,
  43. MyDialogListener listener) {
  44. super(context);
  45. // TODO Auto-generated constructor stub
  46. this.context = context;
  47. this.type = type;
  48. this.fileType = fileType;
  49. this.path = resultPath;
  50. this.listener = listener;
  51. }
  52. @Override
  53. public void dismiss() {
  54. // TODO Auto-generated method stub
  55. super.dismiss();
  56. }
  57. @Override
  58. protected void onCreate(Bundle savedInstanceState) {
  59. // TODO Auto-generated method stub
  60. super.onCreate(savedInstanceState);
  61. setContentView(R.layout.dialog_filechooser);
  62. path = getSDPath();
  63. arr = (ArrayList<String>)getDirs(path);
  64. Adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, arr);
  65. list = (android.widget.ListView)findViewById(R.id.FileChooserDirList);
  66. list.setAdapter(Adapter);
  67. list.setOnItemClickListener(lvLis);
  68. home = (android.widget.Button)findViewById(R.id.FileChooserHomeBtn);
  69. home.setOnClickListener(this);
  70. back = (android.widget.Button)findViewById(R.id.FileChooserBackBtn);
  71. back.setOnClickListener(this);
  72. ok = (android.widget.Button)findViewById(R.id.FileChooserOkBtn);
  73. ok.setOnClickListener(this);
  74. cancel = (android.widget.Button)findViewById(R.id.FileChooserCancelBtn);
  75. cancel.setOnClickListener(this);
  76. layout = (android.widget.LinearLayout)findViewById(R.id.FileChooserDirLayout);
  77. if(type == TypeOpen)
  78. {
  79. // 若為OpenFileDialog,在預留的位置添加TextView,顯示當前路徑
  80. curFilePath = new android.widget.TextView(context);
  81. layout.addView(curFilePath);
  82. curFilePath.setText(path);
  83. }
  84. else if(type == TypeSave)
  85. {
  86. // 若為SaveFileDialog,在預留的位置添加EditText,輸入要保存的文件名
  87. saveFileName = new android.widget.EditText(context);
  88. saveFileName.setWidth(240);
  89. saveFileName.setHeight(70);
  90. saveFileName.setGravity(Gravity.CENTER);
  91. saveFileName.setPadding(0, 2, 0, 0);
  92. layout.addView(saveFileName);
  93. saveFileName.setText("Enter file name");
  94. }
  95. }
  96. // 自動更新ListView內容
  97. Runnable add = new Runnable() {
  98. @Override
  99. public void run() {
  100. // TODO Auto-generated method stub
  101. arr.clear();
  102. List<String> temp = getDirs(path);
  103. for(int i = 0; i < temp.size(); i++) arr.add(temp.get(i));
  104. Adapter.notifyDataSetChanged();
  105. }
  106. };
  107. // 事件監聽,當點擊ListView的某個項目時觸發
  108. private OnItemClickListener lvLis = new OnItemClickListener() {
  109. @Override
  110. public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
  111. String temp = (String)arg0.getItemAtPosition(arg2);
  112. if(temp.equals("..")) path = getSubDir(path); // 如果點擊的項目是"..",表示沒有子目錄,返回上一級目錄
  113. else if(path.equals("/")) path = path + temp; // 如果當前目錄為根目錄,直接添加子目錄,例 "/" -> "/sdcard"
  114. else path = path + "/" + temp; // 將子目錄追加到當前目錄後,例 "/sdcard" -> "/sdcard/xml"
  115. if(type == TypeOpen) curFilePath.setText(path);
  116. Handler handler = new Handler();
  117. handler.post(add);// 因為當前目錄改變,更新子文件夾
  118. }
  119. };
  120. /**
  121. * Get sub directories
  122. * @param ipath
  123. * @return
  124. */
  125. private List<String> getDirs(String ipath) {
  126. List<String> dirs = new ArrayList<String>();
  127. File[] files = new File(ipath).listFiles();
  128. if(files != null)
  129. {
  130. for(File f: files)
  131. {
  132. if(f.isDirectory())
  133. {
  134. String tmp = f.toString();
  135. if(tmp.endsWith("/")) tmp = tmp.substring(0, tmp.length() - 1);
  136. int pos = tmp.lastIndexOf("/");
  137. dirs.add(tmp.substring(pos + 1, tmp.length()));
  138. }
  139. else if(f.isFile() && fileType != null)
  140. {
  141. for(int i = 0; i< fileType.length; i++)
  142. {
  143. int typeStrLen = fileType[i].length();
  144. String fileName = f.getPath().substring(f.getPath().length() - typeStrLen);
  145. if (fileName.equalsIgnoreCase(fileType[i]))
  146. dirs.add(f.toString().substring(path.length() + 1, f.toString().length()));
  147. }
  148. }
  149. }
  150. }
  151. if(dirs.size() == 0) dirs.add("..");
  152. return dirs;
  153. }
  154. @Override
  155. public void onClick(View args0) {
  156. // TODO Auto-generated method stub
  157. if(args0.getId() == home.getId())
  158. {
  159. // 點擊"Home"按鈕,回到根目錄
  160. path = getRootDir();
  161. if(type == TypeOpen) curFilePath.setText(path);
  162. Handler handler = new Handler();
  163. <span style="white-space:pre"> </span>handler.post(add); // 更新子文件夾
  164. }
  165. else if(args0.getId() == back.getId())
  166. {
  167. // 點擊"Back"按鈕,返回上一級文件夾
  168. path = getSubDir(path);
  169. if(type == TypeOpen) curFilePath.setText(path);
  170. Handler handler = new Handler();
  171. handler.post(add); // 更新子文件夾
  172. }
  173. else if(args0.getId() == ok.getId())
  174. {
  175. // 點擊"OK"按鈕,關閉對話框,調用自定義監視器的OnOKClick方法,將當前目錄返回主Activity
  176. dismiss();
  177. listener.OnOkClick(path);
  178. }
  179. else if(args0.getId() == cancel.getId())
  180. {
  181. // 點擊"Cancel”按鈕
  182. this.cancel();
  183. }
  184. }
  185. /**
  186. * Get SD card directory, if SD card not exist, return '/'
  187. * @return
  188. */
  189. private String getSDPath() {
  190. File sdDir = null;
  191. boolean sdCardExist = Environment.getExternalStorageState()
  192. .equals(android.os.Environment.MEDIA_MOUNTED); // 判斷是否存在SD卡
  193. if(sdCardExist)
  194. {
  195. sdDir = Environment.getExternalStorageDirectory(); // 如果SD卡存在,返回SD卡的目錄
  196. }
  197. if(sdDir == null)
  198. {
  199. return "/"; // 如果SD卡不存在,返回根目錄
  200. }
  201. return sdDir.toString();
  202. }
  203. private String getRootDir() {
  204. return "/";
  205. }
  206. /**
  207. * Get upper directory
  208. * @param path
  209. * @return
  210. */
  211. private String getSubDir(String path) {
  212. String subpath = "/";
  213. if(path.endsWith("/"))
  214. {
  215. path = path.substring(0, path.length() - 1);
  216. }
  217. int pos = path.lastIndexOf("/");
  218. if(pos > 0)
  219. {
  220. subpath = path.substring(0, pos);
  221. }
  222. return subpath;
  223. }
  224. }
Copyright © Linux教程網 All Rights Reserved