Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 669|回复: 0

[默认分类] Android开发 打开文件 选择文件对话框

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-5-30 15:26:23 | 显示全部楼层 |阅读模式


      因项目需要打开文件,因此做了一个打开文件的对话框,现在把这部分的代码共享出来了。
    首先是一个回调接口,该接口在文件选择完毕的通知调用者进行如果何种操作。文件接口声明,如下:
      
    1. // filename: CallbackBundle.java
    2. package com.example.openfiledemo;
    3. import android.os.Bundle;
    4. // 简单的Bundle参数回调接口
    5. public interface CallbackBundle {
    6.         abstract void callback(Bundle bundle);
    7. }
    复制代码

    然后的打开文件对话框的一下封装:
      
      
    1. // filename: OpenFileDialog.java
    2. package com.example.openfiledemo;
    3. import java.io.File;
    4. import java.util.ArrayList;
    5. import java.util.HashMap;
    6. import java.util.List;
    7. import java.util.Map;
    8. import android.app.Activity;
    9. import android.app.AlertDialog;
    10. import android.app.Dialog;
    11. import android.content.Context;
    12. import android.os.Bundle;
    13. import android.view.View;
    14. import android.widget.AdapterView;
    15. import android.widget.ListView;
    16. import android.widget.SimpleAdapter;
    17. import android.widget.Toast;
    18. import android.widget.AdapterView.OnItemClickListener;
    19. public class OpenFileDialog {
    20.         public static String tag = "OpenFileDialog";
    21.         static final public String sRoot = "/";
    22.         static final public String sParent = "..";
    23.         static final public String sFolder = ".";
    24.         static final public String sEmpty = "";
    25.         static final private String sOnErrorMsg = "No rights to access!";
    26.        
    27.         // 参数说明
    28.         // context:上下文
    29.         // dialogid:对话框ID
    30.         // title:对话框标题
    31.         // callback:一个传递Bundle参数的回调接口
    32.         // suffix:需要选择的文件后缀,比如需要选择wav、mp3文件的时候设置为".wav;.mp3;",注意最后需要一个分号(;)
    33.         // images:用来根据后缀显示的图标资源ID。
    34.                 //        根目录图标的索引为sRoot;
    35.                 //        父目录的索引为sParent;
    36.                 //        文件夹的索引为sFolder;
    37.                 //        默认图标的索引为sEmpty;
    38.                 //        其他的直接根据后缀进行索引,比如.wav文件图标的索引为"wav"
    39.         public static Dialog createDialog(int id, Context context, String title, CallbackBundle callback, String suffix, Map<String, Integer> images){
    40.                 AlertDialog.Builder builder = new AlertDialog.Builder(context);
    41.                 builder.setView(new FileSelectView(context, id, callback, suffix, images));
    42.                 Dialog dialog = builder.create();
    43.                 //dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    44.                 dialog.setTitle(title);
    45.                 return dialog;
    46.         }
    47.        
    48.         static class FileSelectView extends ListView implements OnItemClickListener{
    49.                
    50.                
    51.                 private CallbackBundle callback = null;
    52.                 private String path = sRoot;
    53.                 private List<Map<String, Object>> list = null;
    54.                 private int dialogid = 0;
    55.                
    56.                 private String suffix = null;
    57.                
    58.                 private Map<String, Integer> imagemap = null;
    59.                
    60.                 public FileSelectView(Context context, int dialogid, CallbackBundle callback, String suffix, Map<String, Integer> images) {
    61.                         super(context);
    62.                         this.imagemap = images;
    63.                         this.suffix = suffix==null?"":suffix.toLowerCase();
    64.                         this.callback = callback;
    65.                         this.dialogid = dialogid;
    66.                         this.setOnItemClickListener(this);
    67.                         refreshFileList();
    68.                 }
    69.                
    70.                 private String getSuffix(String filename){
    71.                         int dix = filename.lastIndexOf(".");
    72.                         if(dix<0){
    73.                                 return "";
    74.                         }
    75.                         else{
    76.                                 return filename.substring(dix+1);
    77.                         }
    78.                 }
    79.                
    80.                 private int getImageId(String s){
    81.                         if(imagemap == null){
    82.                                 return 0;
    83.                         }
    84.                         else if(imagemap.containsKey(s)){
    85.                                 return imagemap.get(s);
    86.                         }
    87.                         else if(imagemap.containsKey(sEmpty)){
    88.                                 return imagemap.get(sEmpty);
    89.                         }
    90.                         else {
    91.                                 return 0;
    92.                         }
    93.                 }
    94.                
    95.                 private int refreshFileList()
    96.                 {
    97.                         // 刷新文件列表
    98.                         File[] files = null;
    99.                         try{
    100.                                 files = new File(path).listFiles();
    101.                         }
    102.                         catch(Exception e){
    103.                                 files = null;
    104.                         }
    105.                         if(files==null){
    106.                                 // 访问出错
    107.                                 Toast.makeText(getContext(), sOnErrorMsg,Toast.LENGTH_SHORT).show();
    108.                                 return -1;
    109.                         }
    110.                         if(list != null){
    111.                                 list.clear();
    112.                         }
    113.                         else{
    114.                                 list = new ArrayList<Map<String, Object>>(files.length);
    115.                         }
    116.                        
    117.                         // 用来先保存文件夹和文件夹的两个列表
    118.                         ArrayList<Map<String, Object>> lfolders = new ArrayList<Map<String, Object>>();
    119.                         ArrayList<Map<String, Object>> lfiles = new ArrayList<Map<String, Object>>();
    120.                        
    121.                         if(!this.path.equals(sRoot)){
    122.                                 // 添加根目录 和 上一层目录
    123.                                 Map<String, Object> map = new HashMap<String, Object>();
    124.                                 map.put("name", sRoot);
    125.                                 map.put("path", sRoot);
    126.                                 map.put("img", getImageId(sRoot));
    127.                                 list.add(map);
    128.                                
    129.                                 map = new HashMap<String, Object>();
    130.                                 map.put("name", sParent);
    131.                                 map.put("path", path);
    132.                                 map.put("img", getImageId(sParent));
    133.                                 list.add(map);
    134.                         }
    135.                        
    136.                         for(File file: files)
    137.                         {
    138.                                 if(file.isDirectory() && file.listFiles()!=null){
    139.                                         // 添加文件夹
    140.                                         Map<String, Object> map = new HashMap<String, Object>();
    141.                                         map.put("name", file.getName());
    142.                                         map.put("path", file.getPath());
    143.                                         map.put("img", getImageId(sFolder));
    144.                                         lfolders.add(map);
    145.                                 }
    146.                                 else if(file.isFile()){
    147.                                         // 添加文件
    148.                                         String sf = getSuffix(file.getName()).toLowerCase();
    149.                                         if(suffix == null || suffix.length()==0 || (sf.length()>0 && suffix.indexOf("."+sf+";")>=0)){
    150.                                                 Map<String, Object> map = new HashMap<String, Object>();
    151.                                                 map.put("name", file.getName());
    152.                                                 map.put("path", file.getPath());
    153.                                                 map.put("img", getImageId(sf));
    154.                                                 lfiles.add(map);
    155.                                         }
    156.                                 }  
    157.                         }
    158.                        
    159.                         list.addAll(lfolders); // 先添加文件夹,确保文件夹显示在上面
    160.                         list.addAll(lfiles);        //再添加文件
    161.                        
    162.                        
    163.                         SimpleAdapter adapter = new SimpleAdapter(getContext(), list, R.layout.filedialogitem, new String[]{"img", "name", "path"}, new int[]{R.id.filedialogitem_img, R.id.filedialogitem_name, R.id.filedialogitem_path});
    164.                         this.setAdapter(adapter);
    165.                         return files.length;
    166.                 }
    167.                 @Override
    168.                 public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    169.                         // 条目选择
    170.                         String pt = (String) list.get(position).get("path");
    171.                         String fn = (String) list.get(position).get("name");
    172.                         if(fn.equals(sRoot) || fn.equals(sParent)){
    173.                                 // 如果是更目录或者上一层
    174.                                 File fl = new File(pt);
    175.                                 String ppt = fl.getParent();
    176.                                 if(ppt != null){
    177.                                         // 返回上一层
    178.                                         path = ppt;
    179.                                 }
    180.                                 else{
    181.                                         // 返回更目录
    182.                                         path = sRoot;
    183.                                 }
    184.                         }
    185.                         else{
    186.                                 File fl = new File(pt);
    187.                                 if(fl.isFile()){
    188.                                         // 如果是文件
    189.                                         ((Activity)getContext()).dismissDialog(this.dialogid); // 让文件夹对话框消失
    190.                                        
    191.                                         // 设置回调的返回值
    192.                                         Bundle bundle = new Bundle();
    193.                                         bundle.putString("path", pt);
    194.                                         bundle.putString("name", fn);
    195.                                         // 调用事先设置的回调函数
    196.                                         this.callback.callback(bundle);
    197.                                         return;
    198.                                 }
    199.                                 else if(fl.isDirectory()){
    200.                                         // 如果是文件夹
    201.                                         // 那么进入选中的文件夹
    202.                                         path = pt;
    203.                                 }
    204.                         }
    205.                         this.refreshFileList();
    206.                 }
    207.         }
    208. }
    复制代码




      
    下面是文件条目的一个布局(文件名:filedialogitem.xml):
      
    1. <?xml version="1.0" encoding="utf-8"?>
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3.     android:id="@+id/vw1"
    4.     android:layout_width="fill_parent"
    5.     android:layout_height="wrap_content"
    6.     android:background="#000000"
    7.     android:orientation="horizontal"
    8.     android:padding="4dp" >
    9.     <ImageView
    10.         android:id="@+id/filedialogitem_img"
    11.         android:layout_width="32dp"
    12.         android:layout_height="32dp"
    13.         android:layout_margin="4dp"/>
    14.    <LinearLayout
    15.        android:layout_width="wrap_content"
    16.        android:layout_height="wrap_content"
    17.        android:orientation="vertical" >
    18.         <TextView
    19.             android:id="@+id/filedialogitem_name"
    20.             android:layout_width="fill_parent"
    21.             android:layout_height="wrap_content"
    22.             android:textColor="#FFFFFF"
    23.             android:textSize="18sp"
    24.             android:textStyle="bold" />
    25.         <TextView
    26.             android:id="@+id/filedialogitem_path"
    27.             android:layout_width="fill_parent"
    28.             android:layout_height="wrap_content"
    29.             android:paddingLeft="10dp"
    30.             android:textColor="#FFFFFF"
    31.             android:textSize="14sp" />
    32.     </LinearLayout>
    33. </LinearLayout>
    复制代码

    下面是使用的例子:
      
      
    1. // filename: OpenFileDemo.java
    2. package com.example.openfiledemo;
    3. import java.util.HashMap;
    4. import java.util.Map;
    5. import android.os.Bundle;
    6. import android.app.Activity;
    7. import android.app.Dialog;
    8. import android.view.View;
    9. import android.view.View.OnClickListener;
    10. public class OpenFileDemo extends Activity {
    11.        
    12.         static private int openfileDialogId = 0;
    13.        
    14.     @Override
    15.     public void onCreate(Bundle savedInstanceState) {
    16.         super.onCreate(savedInstanceState);
    17.         setContentView(R.layout.activity_open_file_demo);
    18.         
    19.         
    20.         // 设置单击按钮时打开文件对话框
    21.         findViewById(R.id.button_openfile).setOnClickListener(new OnClickListener() {
    22.                         @Override
    23.                         public void onClick(View arg0) {
    24.                                 showDialog(openfileDialogId);
    25.                         }
    26.                 });
    27.     }
    28.         @Override
    29.         protected Dialog onCreateDialog(int id) {
    30.                 if(id==openfileDialogId){
    31.                         Map<String, Integer> images = new HashMap<String, Integer>();
    32.                         // 下面几句设置各文件类型的图标, 需要你先把图标添加到资源文件夹
    33.                         images.put(OpenFileDialog.sRoot, R.drawable.filedialog_root);        // 根目录图标
    34.                         images.put(OpenFileDialog.sParent, R.drawable.filedialog_folder_up);        //返回上一层的图标
    35.                         images.put(OpenFileDialog.sFolder, R.drawable.filedialog_folder);        //文件夹图标
    36.                         images.put("wav", R.drawable.filedialog_wavfile);        //wav文件图标
    37.                         images.put(OpenFileDialog.sEmpty, R.drawable.filedialog_root);
    38.                         Dialog dialog = OpenFileDialog.createDialog(id, this, "打开文件", new CallbackBundle() {
    39.                                 @Override
    40.                                 public void callback(Bundle bundle) {
    41.                                         String filepath = bundle.getString("path");
    42.                                         setTitle(filepath); // 把文件路径显示在标题上
    43.                                 }
    44.                         },
    45.                         ".wav;",
    46.                         images);
    47.                         return dialog;
    48.                 }
    49.                 return null;
    50.         }
    51. }
    复制代码

      


    工程源代码:  https://pan.baidu.com/s/1mh7Z3YS

    放两张效果图:







    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-5-17 19:53 , Processed in 0.864876 second(s), 37 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表