Android基础教程:简易的文件对话框


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.   
  7.     <LinearLayout android:orientation="horizontal"  
  8.                   android:layout_width="fill_parent"  
  9.                   android:layout_height="40dip">  
  10.                     
  11.         <Button android:layout_width="40dip"  
  12.                 android:layout_height="40dip"  
  13.                 android:id="@+id/FileChooserHomeBtn"  
  14.                 android:text="Home"  
  15.                 android:layout_weight="1"/>  
  16.                   
  17.         <LinearLayout android:layout_width="140dip"  
  18.                       android:layout_height="35dip"  
  19.                       android:id="@+id/FileChooserDirLayout"  
  20.                       android:gravity="center"  
  21.                       android:layout_weight="1">  
  22.                         
  23.             <!--  <TextView android:layout_width="140dip"   
  24.                             android:layout_height="35dip"  
  25.                             android:id="@+id/dir_str"  
  26.                             android:gravity="center"  
  27.                             android:layout_weight="1"/> -->  
  28.           
  29.         </LinearLayout>  
  30.       
  31.         <Button android:layout_width="40dip"  
  32.                 android:layout_height="40dip"  
  33.                 android:id="@+id/FileChooserBackBtn"  
  34.                 android:text="Back"  
  35.                 android:layout_weight="1"/>  
  36.                   
  37.     </LinearLayout>  
  38.       
  39.     <ListView android:layout_width="fill_parent"  
  40.               android:layout_height="300dip"  
  41.               android:id="@+id/FileChooserDirList"/>  
  42.                 
  43.     <Button android:layout_width="fill_parent"  
  44.             android:layout_height="wrap_content"  
  45.             android:id="@+id/FileChooserOkBtn"  
  46.             android:text="OK"/>  
  47.                 
  48.     <Button android:layout_width="fill_parent"  
  49.             android:layout_height="wrap_content"  
  50.             android:id="@+id/FileChooserCancelBtn"  
  51.             android:text="Cancel"/>  
  52.               
  53. </LinearLayout>  
2.Dialog的java文件
  1. import java.io.File;  
  2. import java.util.ArrayList;  
  3. import java.util.List;  
  4.   
  5. import android.app.Dialog;  
  6. import android.content.Context;  
  7. import android.os.Bundle;  
  8. import android.os.Environment;  
  9. import android.os.Handler;  
  10. import android.view.Gravity;  
  11. import android.view.View;  
  12. import android.widget.AdapterView;  
  13. import android.widget.AdapterView.OnItemClickListener;  
  14. import android.widget.ArrayAdapter;  
  15.   
  16.   
  17. /** 
  18.  * 
  19.  * 
  20.  * 
  21.  * @author 
  22.  * 
  23.  */  
  24. public class FileOpenerDialog extends Dialog implements android.view.View.OnClickListener {  
  25.       
  26.     private android.widget.ListView list;  
  27.     ArrayAdapter<String> Adapter;  
  28.     ArrayList<String> arr = new ArrayList<String>();  
  29.       
  30.     Context context;  
  31.     private String path;  
  32.       
  33.     private android.widget.TextView curFilePath;  
  34.     private android.widget.EditText saveFileName;  
  35.     private android.widget.Button home, back, ok, cancel;  
  36.     private android.widget.LinearLayout layout;  
  37.       
  38.     private int type = 1;  
  39.     private String[] fileType = null;  
  40.       
  41.     public final static int TypeOpen = 1;  
  42.     public final static int TypeSave = 2;  
  43.       
  44.     private MyDialogListener listener;  
  45.       
  46.     /** 
  47.      * @param context 
  48.      * @param 值为1表示OpenFileDialog, 值为2表示SaveFileDialog 
  49.      * @param 需要过滤的文件类型,若为空表示只显示文件夹 
  50.      * @param 初始路径,这个有问题 
  51.      */  
  52.     public FileOpenerDialog(Context context, int type, String[] fileType, String resultPath,  
  53.             MyDialogListener listener) {  
  54.         super(context);  
  55.         // TODO Auto-generated constructor stub   
  56.         this.context = context;  
  57.         this.type = type;  
  58.         this.fileType = fileType;  
  59.         this.path = resultPath;  
  60.         this.listener = listener;  
  61.     }  
  62.       
  63.     @Override  
  64.     public void dismiss() {  
  65.         // TODO Auto-generated method stub   
  66.         super.dismiss();  
  67.     }  
  68.       
  69.     @Override  
  70.     protected void onCreate(Bundle savedInstanceState) {  
  71.         // TODO Auto-generated method stub   
  72.         super.onCreate(savedInstanceState);  
  73.         setContentView(R.layout.dialog_filechooser);  
  74.           
  75.         path = getSDPath();  
  76.         arr = (ArrayList<String>)getDirs(path);  
  77.         Adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, arr);  
  78.           
  79.         list = (android.widget.ListView)findViewById(R.id.FileChooserDirList);  
  80.         list.setAdapter(Adapter);         
  81.         list.setOnItemClickListener(lvLis);  
  82.   
  83.         home = (android.widget.Button)findViewById(R.id.FileChooserHomeBtn);  
  84.         home.setOnClickListener(this);  
  85.           
  86.         back = (android.widget.Button)findViewById(R.id.FileChooserBackBtn);  
  87.         back.setOnClickListener(this);  
  88.           
  89.         ok = (android.widget.Button)findViewById(R.id.FileChooserOkBtn);  
  90.         ok.setOnClickListener(this);  
  91.           
  92.         cancel = (android.widget.Button)findViewById(R.id.FileChooserCancelBtn);  
  93.         cancel.setOnClickListener(this);  
  94.           
  95.         layout = (android.widget.LinearLayout)findViewById(R.id.FileChooserDirLayout);  
  96.           
  97.         if(type == TypeOpen)   
  98.         {  
  99.                         // 若为OpenFileDialog,在预留的位置添加TextView,显示当前路径   
  100.             curFilePath = new android.widget.TextView(context);  
  101.             layout.addView(curFilePath);  
  102.             curFilePath.setText(path);  
  103.         }  
  104.         else if(type == TypeSave)  
  105.         {  
  106.                         // 若为SaveFileDialog,在预留的位置添加EditText,输入要保存的文件名   
  107.             saveFileName = new android.widget.EditText(context);  
  108.             saveFileName.setWidth(240);  
  109.             saveFileName.setHeight(70);  
  110.             saveFileName.setGravity(Gravity.CENTER);  
  111.             saveFileName.setPadding(0200);  
  112.             layout.addView(saveFileName);  
  113.             saveFileName.setText("Enter file name");  
  114.         }  
  115.     }  
  116.           
  117.     // 自动更新ListView内容   
  118.     Runnable add = new Runnable() {  
  119.         @Override  
  120.         public void run() {  
  121.             // TODO Auto-generated method stub   
  122.             arr.clear();  
  123.             List<String> temp = getDirs(path);  
  124.             for(int i = 0; i < temp.size(); i++) arr.add(temp.get(i));  
  125.             Adapter.notifyDataSetChanged();  
  126.         }         
  127. };  
  128.      
  129.     // 事件监听,当点击ListView的某个项目时触发   
  130.     private OnItemClickListener lvLis = new OnItemClickListener() {  
  131.         @Override  
  132.         public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {  
  133.             String temp = (String)arg0.getItemAtPosition(arg2);       
  134.             if(temp.equals(".."))   path = getSubDir(path);   // 如果点击的项目是"..",表示没有子目录,返回上一级目录   
  135.             else if(path.equals("/"))   path = path + temp;   // 如果当前目录为根目录,直接添加子目录,例 "/" -> "/sdcard"   
  136.             else    path = path + "/" + temp;   // 将子目录追加到当前目录后,例 "/sdcard" -> "/sdcard/xml"   
  137.             if(type == TypeOpen)    curFilePath.setText(path);     
  138.             Handler handler = new Handler();  
  139.            handler.post(add);// 因为当前目录改变,更新子文件夹   
  140.         }  
  141.    };  
  142.       
  143.     /** 
  144.      * Get sub directories 
  145.      * @param ipath 
  146.      * @return 
  147.      */  
  148.     private List<String> getDirs(String ipath) {  
  149.         List<String> dirs = new ArrayList<String>();          
  150.         File[] files = new File(ipath).listFiles();  
  151.         if(files != null)  
  152.         {  
  153.             for(File f: files)  
  154.             {  
  155.                 if(f.isDirectory())  
  156.                 {  
  157.                     String tmp = f.toString();  
  158.                     if(tmp.endsWith("/"))   tmp = tmp.substring(0, tmp.length() - 1);  
  159.                     int pos = tmp.lastIndexOf("/");  
  160.                     dirs.add(tmp.substring(pos + 1, tmp.length()));  
  161.                 }  
  162.                 else if(f.isFile() && fileType != null)  
  163.                 {  
  164.                     for(int i = 0; i< fileType.length; i++)  
  165.                     {  
  166.                         int typeStrLen = fileType[i].length();  
  167.                         String fileName = f.getPath().substring(f.getPath().length() - typeStrLen);  
  168.                         if (fileName.equalsIgnoreCase(fileType[i]))  
  169.                             dirs.add(f.toString().substring(path.length() + 1, f.toString().length()));  
  170.                     }  
  171.                 }  
  172.             }  
  173.         }  
  174.         if(dirs.size() == 0)    dirs.add("..");  
  175.         return dirs;  
  176.     }  
  177.       
  178.     @Override  
  179.     public void onClick(View args0) {  
  180.         // TODO Auto-generated method stub   
  181.         if(args0.getId() == home.getId())   
  182.         {  
  183.                         // 点击"Home"按钮,回到根目录   
  184.             path = getRootDir();  
  185.             if(type == TypeOpen)    curFilePath.setText(path);  
  186.             Handler handler = new Handler();  
  187.             <span style="white-space:pre">    </span>handler.post(add);   // 更新子文件夹   
  188.         }  
  189.         else if(args0.getId() == back.getId())  
  190.         {  
  191.                         // 点击"Back"按钮,返回上一级文件夹   
  192.             path = getSubDir(path);  
  193.             if(type == TypeOpen)    curFilePath.setText(path);  
  194.             Handler handler = new Handler();  
  195.             handler.post(add);   // 更新子文件夹   
  196.         }  
  197.         else if(args0.getId() == ok.getId())  
  198.         {  
  199.                         // 点击"OK"按钮,关闭对话框,调用自定义监视器的OnOKClick方法,将当前目录返回主Activity   
  200.             dismiss();  
  201.             listener.OnOkClick(path);  
  202.         }  
  203.         else if(args0.getId() == cancel.getId())   
  204.         {  
  205.                         // 点击"Cancel”按钮   
  206.             this.cancel();  
  207.         }  
  208.     }  
  209.       
  210.     /** 
  211.      * Get SD card directory, if SD card not exist, return '/' 
  212.      * @return 
  213.      */  
  214.     private String getSDPath() {   
  215.         File sdDir = null;  
  216.         boolean sdCardExist = Environment.getExternalStorageState()  
  217.                 .equals(android.os.Environment.MEDIA_MOUNTED);   // 判断是否存在SD卡   
  218.         if(sdCardExist)  
  219.         {  
  220.             sdDir = Environment.getExternalStorageDirectory();   // 如果SD卡存在,返回SD卡的目录   
  221.         }  
  222.         if(sdDir == null)  
  223.         {  
  224.             return "/";   // 如果SD卡不存在,返回根目录   
  225.         }  
  226.         return sdDir.toString();  
  227.     }   
  228.   
  229.     private String getRootDir() {  
  230.         return "/";  
  231.     }  
  232.       
  233.     /** 
  234.      * Get upper directory 
  235.      * @param path 
  236.      * @return 
  237.      */  
  238.     private String getSubDir(String path) {  
  239.         String subpath = "/";  
  240.         if(path.endsWith("/"))  
  241.         {  
  242.             path = path.substring(0, path.length() - 1);  
  243.         }  
  244.         int pos = path.lastIndexOf("/");          
  245.         if(pos > 0)  
  246.         {  
  247.             subpath = path.substring(0, pos);  
  248.         }  
  249.         return subpath;  
  250.     }    
  251. }  
  • 1
  • 2
  • 下一页

相关内容