Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 非常簡單的Android打開和保存對話框功能

非常簡單的Android打開和保存對話框功能

編輯:關於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"" rel="nofollow" target="_blank">http://schemas.android.com/apk/res/android"</a>
  xmlns:tools="<a href="http://schemas.android.com/tools"" 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"" rel="nofollow" target="_blank">http://schemas.android.com/apk/res/android"</a>

  xmlns:tools="<a href="http://schemas.android.com/tools"" 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);

    }

  }

}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved