Very simple Android Open and Save dialog box features _android

Source: Internet
Author: User

There are no standard open and Save As dialog boxes on Android. In this code, I'll describe in detail a very simple implementation of the Open and Save dialog box, which is very useful for Android beginners, and dialog boxes are full screen active.

Main function:

1, access to any directory SD card
2, recursive access to the folder
3. Single File Selection
4, by pressing the Hardware Back button upgrade
5. Confirm File Select OK button

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:l ayout_weight= "1" > </ListView> <linearlayout android:layout_width= "Match_parent" Android:layout_h eight= "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" Andr

 oid: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 (s)
    Avedinstancestate);
    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 () + "/");
          The 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.getn
      Ame ());
      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 &lT 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.getexternalstoragedirector

    Y (). 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" > <ListVi

    EW 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= "ten" android:text= "file.txt" > <linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" Andro id:orientation= "Horizontal" > <button AndrOid:id= "@+id/sfa_btnok" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Andro id: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:te

 xt= "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 () + "/");

          The 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.ge

      Tname ());

      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.getexternalstoragedirector

    Y (). 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);

 }

  }

}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.