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

 更新时间:2016年07月15日 10:29:06   投稿:lijiao  
这篇文章主要介绍了非常简单的Android打开和保存对话框功能,感兴趣的小伙伴们可以参考一下

在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 Studio 4.1 更新内容

    浅谈Android Studio 4.1 更新内容

    这篇文章主要介绍了浅谈Android Studio 4.1 更新内容,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10
  • Android自定义简单的顶部标题栏

    Android自定义简单的顶部标题栏

    这篇文章主要为大家详细介绍了Android自定义简单的顶部标题栏,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-11-11
  • Android 实现获取手机里面的所有图片详解及实例

    Android 实现获取手机里面的所有图片详解及实例

    这篇文章主要介绍了Android 实现获取手机里面的所有图片详解及实例的相关资料,需要的朋友可以参考下
    2017-05-05
  • 自定义搜索功能Android实现

    自定义搜索功能Android实现

    这篇文章主要为大家详细介绍了自定义搜索功能,由Android代码实现,感兴趣的小伙伴们可以参考一下
    2016-05-05
  • Android Intent实现页面跳转的方法示例

    Android Intent实现页面跳转的方法示例

    本篇文章主要介绍了Android Intent实现页面跳转的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-03-03
  • 深入学习Android ANR 的原理分析及解决办法

    深入学习Android ANR 的原理分析及解决办法

    Android系统中,AMS和WMS会检测App的响应时间,如果App在特定时间无法相应屏幕触摸或键盘输入时间,或者特定事件没有处理完毕,就会出现ANR。本文将带领大学深入学习一下ANR的原理及解决办法,感兴趣的同学可以学习一下
    2021-11-11
  • Android开发 -- setTag的妙用和The key must be an application-specific resource id 异常

    Android开发 -- setTag的妙用和The key must be an application-specif

    本文主要介绍Android开发setTag的妙用,小编觉得挺实用的,给大家一个参考,希望对大家学习有所帮助。
    2016-06-06
  • Android设置PreferenceCategory背景颜色的方法

    Android设置PreferenceCategory背景颜色的方法

    这篇文章主要介绍了Android设置PreferenceCategory背景颜色的方法,涉及Android设置背景色的技巧,需要的朋友可以参考下
    2015-05-05
  • android studio按钮监听的5种方法实例详解

    android studio按钮监听的5种方法实例详解

    这篇文章主要介绍了android studio按钮监听的5种方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-03-03
  • Android对话框AlertDialog详解

    Android对话框AlertDialog详解

    本文详细讲解了Android对话框AlertDialog的实现方式,文中通过示例代码介绍的非常详细。对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-12-12

最新评论