非常简单的Android打开和保存对话框功能

所属分类: 软件编程 / Android 阅读数: 1097
收藏 0 赞 0 分享

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

主要功能:

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

activity_open_file.xml

<LinearLayout xmlns:android="<a href="http://schemas.android.com/apk/res/android&quot;" rel="nofollow" target="_blank">http://schemas.android.com/apk/res/android"</a>
  xmlns:tools="<a href="http://schemas.android.com/tools&quot;" rel="nofollow" target="_blank">http://schemas.android.com/tools"</a>
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

  <ListView
    android:id="@+id/LvList"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1" >

  </ListView>
  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
      android:id="@+id/BtnOK"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:text="OK" />
    <Button
      android:id="@+id/BtnCancel"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:text="Cancel" />

  </LinearLayout>
</LinearLayout>

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<String> listItems = new ArrayList<String>();
  ArrayAdapter<String> 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<String> folders = new ArrayList<String>();
    ArrayList<String> files = new ArrayList<String>();
    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<String>() {
      @Override
      public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);
      }
    });

     Collections.sort(files, new Comparator<String>() {
      @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<String>(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)

          + "<span>[</span>" + entryName + "]");

    }

  }

}

activity_save_file.xml

<LinearLayout xmlns:android="<a href="http://schemas.android.com/apk/res/android&quot;" rel="nofollow" target="_blank">http://schemas.android.com/apk/res/android"</a>

  xmlns:tools="<a href="http://schemas.android.com/tools&quot;" rel="nofollow" target="_blank">http://schemas.android.com/tools"</a>

  android:layout_width="match_parent"

  android:layout_height="match_parent"

  android:orientation="vertical" >


  <ListView

    android:id="@+id/SFA_LvList"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:layout_weight="1" >

  </ListView>


  <EditText

    android:id="@+id/SFA_TxtFileName"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:ems="10"

    android:text="file.txt" />

  

  <LinearLayout

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:orientation="horizontal" >


    <Button

      android:id="@+id/SFA_BtnOK"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:layout_weight="1"

      android:text="OK" />


    <Button

      android:id="@+id/SFA_BtnCancel"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:layout_weight="1"

      android:text="Cancel" />

    

  </LinearLayout>

    

</LinearLayout>
</LinearLayout>

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<String> listItems = new ArrayList<String>();

    

    ArrayAdapter<String> 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<String> folders = new ArrayList<String>();

    

    ArrayList<String> files = new ArrayList<String>();

    

    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<String>() {

      @Override

      public int compare(String s1, String s2) {

        return s1.compareToIgnoreCase(s2);

      }

    });

    

    Collections.sort(files, new Comparator<String>() {

      @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<String>(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)

          + "<span>[</span>" + entryName + "]");

      

      TxtFileName.setText(entryName);

    }

  }

}

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

更多精彩内容其他人还在看

Android网络编程之获取网络上的Json数据实例

这篇文章主要介绍了Android网络编程之获取网络上的Json数据实例,本文用完整的代码实例讲解了在Android中读取网络中Json数据的方法,需要的朋友可以参考下
收藏 0 赞 0 分享

Android中的windowSoftInputMode属性详解

这篇文章主要介绍了Android中的windowSoftInputMode属性详解,本文对windowSoftInputMode的9个属性做了详细总结,需要的朋友可以参考下
收藏 0 赞 0 分享

Android网络编程之UDP通信模型实例

这篇文章主要介绍了Android网络编程之UDP通信模型实例,本文给出了服务端代码和客户端代码,需要的朋友可以参考下
收藏 0 赞 0 分享

Android中使用ListView实现漂亮的表格效果

这篇文章主要介绍了Android中使用ListView实现漂亮的表格效果,本文用详细的代码实例创建了一个股票行情表格,需要的朋友可以参考下
收藏 0 赞 0 分享

Android中刷新界面的二种方法

这篇文章主要介绍了Android中刷新界面的二种方法,本文使用Handler、postInvalidate两种方法实现界面刷新,需要的朋友可以参考下
收藏 0 赞 0 分享

Android SDK三种更新失败及其解决方法

这篇文章主要介绍了Android SDK三种更新失败及其解决方法,需要的朋友可以参考下
收藏 0 赞 0 分享

Android学习笔记——Menu介绍(一)

Android3.0(API level 11)开始,Android设备不再需要专门的菜单键。随着这种变化,Android app应该取消对传统6项菜单的依赖。取而代之的是提供anction bar来提供基本的用户功能
收藏 0 赞 0 分享

Android学习笔记——Menu介绍(二)

这次将继续上一篇文章没有讲完的Menu的学习,上下文菜单(Context menu)和弹出菜单(Popup menu)
收藏 0 赞 0 分享

Android学习笔记——Menu介绍(三)

今天继续昨天没有讲完的Menu的学习,主要是Popup Menu的学习,需要的朋友可以参考下
收藏 0 赞 0 分享

Android显示网络图片实例

这篇文章主要介绍了Android显示网络图片的方法,以实例形式展示了Android程序显示网络图片的方法,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多