在Android上没有标准的打开和另存为对话框。在本代码中,我将详细描述一个非常简单的打开和保存对话框实现过程,对于Android初学者来说非常有用,对话框都是全屏活动的。

主要功能:

1、访问任何目录的SD卡
2、递归访问文件夹
3、单一文件选择
4、通过按硬件后退按钮升级
5、确认文件选择OK按钮
 

activity_open_file.xml

          

OpenFileActivity.java

package com.example.androidfiledialogs;import java.io.File;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.os.Environment;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.AdapterView.OnItemLongClickListener;import android.widget.AdapterView.OnItemSelectedListener;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.ListView;import android.widget.Spinner;import android.widget.Toast;public class OpenFileActivity extends Activity  implements OnClickListener, OnItemClickListener {  ListView LvList;  ArrayList listItems = new ArrayList();  ArrayAdapter adapter;  Button BtnOK;  Button BtnCancel;  String currentPath = null;  String selectedFilePath = null; /* Full path, i.e. /mnt/sdcard/folder/file.txt */  String selectedFileName = null; /* File Name Only, i.e file.txt */  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_open_file);    try {      /* Initializing Widgets */      LvList = (ListView) findViewById(R.id.LvList);      BtnOK = (Button) findViewById(R.id.BtnOK);      BtnCancel = (Button) findViewById(R.id.BtnCancel);          /* Initializing Event Handlers */      LvList.setOnItemClickListener(this);      BtnOK.setOnClickListener(this);      BtnCancel.setOnClickListener(this);      //    setCurrentPath(Environment.getExternalStorageDirectory().getAbsolutePath() + "/");    } catch (Exception ex) {      Toast.makeText(this,          "Error in OpenFileActivity.onCreate: " + ex.getMessage(),          Toast.LENGTH_SHORT).show();    }  }  void setCurrentPath(String path) {    ArrayList folders = new ArrayList();    ArrayList files = new ArrayList();    currentPath = path;    File allEntries = new File(path).listFiles();    for (int i = 0; i < allEntries.length; i++) {      if (allEntries.isDirectory()) {        folders.add(allEntries.getName());      } else if (allEntries.isFile()) {        files.add(allEntries.getName());      }    }    Collections.sort(folders, new Comparator() {      @Override      public int compare(String s1, String s2) {        return s1.compareToIgnoreCase(s2);      }    });     Collections.sort(files, new Comparator() {      @Override      public int compare(String s1, String s2) {        return s1.compareToIgnoreCase(s2);      }    });    listItems.clear();    for (int i = 0; i < folders.size(); i++) {      listItems.add(folders.get(i) + "/");    }    for (int i = 0; i < files.size(); i++) {      listItems.add(files.get(i));    }        adapter = new ArrayAdapter(this,        android.R.layout.simple_list_item_1,        listItems);    adapter.notifyDataSetChanged();        LvList.setAdapter(adapter);  }    @Override  public void onBackPressed()  {    if (!currentPath.equals(Environment.getExternalStorageDirectory().getAbsolutePath() + "/")) {      setCurrentPath(new File(currentPath).getParent() + "/");    } else {      super.onBackPressed();    }  }    @Override  public void onClick(View v) {    Intent intent;        switch (v.getId()) {    case R.id.BtnOK:            intent = new Intent();      intent.putExtra("fileName", selectedFilePath);      intent.putExtra("shortFileName", selectedFileName);      setResult(RESULT_OK, intent);            this.finish();            break;    case R.id.BtnCancel:            intent = new Intent();      intent.putExtra("fileName", "");      intent.putExtra("shortFileName", "");      setResult(RESULT_CANCELED, intent);            this.finish();            break;    }  }  @Override  public void onItemClick(AdapterView<?> parent, View view, int position,      long id) {    String entryName = (String)parent.getItemAtPosition(position);    if (entryName.endsWith("/")) {      setCurrentPath(currentPath + entryName);    } else {      selectedFilePath = currentPath + entryName;            selectedFileName = entryName;            this.setTitle(this.getResources().getString(R.string.title_activity_open_file)          + "[" + entryName + "]");    }  }}

activity_save_file.xml

              

SaveFileActivity.java

package com.example.androidfiledialogs;import java.io.File;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.os.Environment;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import android.widget.Toast;import android.widget.AdapterView.OnItemClickListener;public class SaveFileActivity extends Activity  implements OnClickListener, OnItemClickListener {    ListView LvList;        ArrayList listItems = new ArrayList();        ArrayAdapter adapter;        EditText TxtFileName;        Button BtnOK;    Button BtnCancel;        String currentPath = null;      @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_save_file);        try {      /* Initializing Widgets */      LvList = (ListView) findViewById(R.id.SFA_LvList);      TxtFileName = (EditText) findViewById(R.id.SFA_TxtFileName);      BtnOK = (Button) findViewById(R.id.SFA_BtnOK);      BtnCancel = (Button) findViewById(R.id.SFA_BtnCancel);            /* Initializing Event Handlers */            LvList.setOnItemClickListener(this);            BtnOK.setOnClickListener(this);      BtnCancel.setOnClickListener(this);            //            setCurrentPath(Environment.getExternalStorageDirectory().getAbsolutePath() + "/");    } catch (Exception ex) {      Toast.makeText(this,          "Error in SaveFileActivity.onCreate: " + ex.getMessage(),          Toast.LENGTH_SHORT).show();    }  }    void setCurrentPath(String path) {    ArrayList folders = new ArrayList();        ArrayList files = new ArrayList();        currentPath = path;        File allEntries = new File(path).listFiles();        for (int i = 0; i < allEntries.length; i++) {      if (allEntries.isDirectory()) {        folders.add(allEntries.getName());      } else if (allEntries.isFile()) {        files.add(allEntries.getName());      }    }        Collections.sort(folders, new Comparator() {      @Override      public int compare(String s1, String s2) {        return s1.compareToIgnoreCase(s2);      }    });        Collections.sort(files, new Comparator() {      @Override      public int compare(String s1, String s2) {        return s1.compareToIgnoreCase(s2);      }    });        listItems.clear();        for (int i = 0; i < folders.size(); i++) {      listItems.add(folders.get(i) + "/");    }        for (int i = 0; i < files.size(); i++) {      listItems.add(files.get(i));    }        adapter = new ArrayAdapter(this,        android.R.layout.simple_list_item_1,        listItems);    adapter.notifyDataSetChanged();        LvList.setAdapter(adapter);  }    @Override  public void onBackPressed()  {    if (!currentPath.equals(Environment.getExternalStorageDirectory().getAbsolutePath() + "/")) {      setCurrentPath(new File(currentPath).getParent() + "/");    } else {      super.onBackPressed();    }  }    @Override  public void onClick(View v) {    Intent intent;        switch (v.getId()) {    case R.id.SFA_BtnOK:            intent = new Intent();      intent.putExtra("fileName", currentPath + TxtFileName.getText().toString());      intent.putExtra("shortFileName", TxtFileName.getText().toString());      setResult(RESULT_OK, intent);            this.finish();            break;    case R.id.SFA_BtnCancel:            intent = new Intent();      intent.putExtra("fileName", "");      intent.putExtra("shortFileName", "");      setResult(RESULT_CANCELED, intent);            this.finish();            break;    }  }  @Override  public void onItemClick(AdapterView<?> parent, View view, int position,      long id) {    String entryName = (String)parent.getItemAtPosition(position);    if (entryName.endsWith("/")) {      setCurrentPath(currentPath + entryName);    } else {      this.setTitle(this.getResources().getString(R.string.title_activity_open_file)          + "[" + entryName + "]");            TxtFileName.setText(entryName);    }  }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多相关文章

  1. C语言函数的递归(上)
  2. Android之AlertDialog的基础使用
  3. 一起学android之利用回调函数onCreateDialog实现加载对话框(23)
  4. Android耳机线控详解,蓝牙耳机按钮监听(仿酷狗线控效果)
  5. 0基础,安卓搭建环境,运行HelloWord
  6. android 按钮自定义
  7. android Tools之Hierachy Viewer的使用
  8. 网格布局(计算器界面设计)
  9. Android中的Dialog用法讲解大全

随机推荐

  1. android休眠与唤醒驱动流程分析
  2. Android中各种onTouch事件
  3. Android中Activity多页滑动切换效果(使用V
  4. 相对布局
  5. android 设置缓存工具类
  6. android 代码混淆之后 微信分享不起作用
  7. compileSdkVersion、buildToolsVersion、
  8. Android使用了ProGuard时注意的事项
  9. Android(安卓)解析IMEI
  10. android触摸实现方式