Implementation of Android applications select Local files to share with directory instances _android

Source: Internet
Author: User
Tags stub

File Selector
today to share the role of the file selector, specifically to get the user in the SD card selected file/folder path, similar to C # in the OpenFileDialog control (C # One-stop development or obsession). function to achieve a relatively simple, mainly to help you save development time.
A wide spread on the Internet a finished product as follows <[android instance] File Selector, this article is based on the finished product modified to make it easier to understand, more efficient. In addition, the main features are:
1, we monitor the user to press the Back button event, so that it returned to the previous level of directory;
2. Special treatment is made for different file types (file vs folder, target file vs other file).
Knowledge point One, use of the File class
The main features of the file selector are: Browse files \ folders, file types, etc., all through the Java file class.

Knowledge point two, call method description
Use the Startactivityforresult () initiation Call and the Onactivityresult () method to accept the callback information.
Screenshot below:

The other is nothing to say, we look at code comments ~ ~ So easy--.

Filechooseractivity.java the class that implements the file selection.

public class Copyoffilechooseractivity extends activity {private String msdcardrootpath;//sdcard Root Path private  String Mlastfilepath; 
  The path currently displayed private arraylist<fileinfo> mfilelists; 
   
  Private Filechooseradapter Madatper; 
    Configure the adapter private void Setgridviewadapter (String filePath) {updatefileitems (FilePath); 
    Madatper = new Filechooseradapter (this, mfilelists); 
  Mgridview.setadapter (Madatper); 
    ///Update the data according to the path and notify the Adatper data to change the private void Updatefileitems (String filePath) {mlastfilepath = FilePath; 
     
    Mtvpath.settext (Mlastfilepath); 
    if (mfilelists = = null) mfilelists = new arraylist<fileinfo> (); 
     
    if (!mfilelists.isempty ()) mfilelists.clear (); 
    file[] files = Folderscan (FilePath); 
    if (files = null) return; 
       
      for (int i = 0; i < files.length i++) {if (Files[i].ishidden ())//Do not show hidden file continue; String Fileabsolutepath = files[i].GetAbsolutePath (); 
      String fileName = Files[i].getname (); 
      Boolean isdirectory = false; 
      if (Files[i].isdirectory ()) {isdirectory = true; 
      } FileInfo FileInfo = new FileInfo (Fileabsolutepath, FileName, isdirectory); 
    Add to List Mfilelists.add (FileInfo); //when the object of Madatper don ' t initialized if (madatper!= null) Madatper.notifydatas Etchanged (); 
    Re-refresh}//Get all files of the current path private file[] Folderscan (String path) {File File = new file (path); 
    file[] files = file.listfiles (); 
  return files; Private Adapterview.onitemclicklistener Mitemclicklistener = new Onitemclicklistener () {public void Onitemclick (adapterview<?> Adapterview, view view, int position, long ID) 
      {FileInfo FileInfo = (FileInfo) ((Filechooseradapter) Adapterview.getadapter ()). GetItem (position)); if (Fileinfo.isdirectory ())//Click the item as a folder, display all files under the folder UpdatefileItems (Fileinfo.getfilepath ()); 
        else if (Fileinfo.ispptfile ()) {//is a PPT file, the path is notified to the caller Intent Intent = new Intent (); 
        Intent.putextra (Extra_file_chooser, Fileinfo.getfilepath ()); 
        Setresult (RESULT_OK, intent); 
      Finish (); 
      } else {//other files ... toast (GetText (R.string.open_file_error_format)); 
  } 
    } 
  }; public boolean onKeyDown (int keycode, keyevent event) {if (event.getaction () = = Keyevent.action_down && Event   
      . getKeyCode () = = Keyevent.keycode_back) {backprocess (); 
    return true; 
  Return Super.onkeydown (KeyCode, event); 
    //Returns the operation of the previous directory The public void Backprocess () {//Determines whether the current path is a sdcard path, and if not, goes back to the previous layer. 
      if (!mlastfilepath.equals (Msdcardrootpath)) {File Thisfile = new file (Mlastfilepath); 
      String Parentfilepath = Thisfile.getparent (); 
    Updatefileitems (Parentfilepath); else {//is the sdcard path, directly ending Setresult (result_canceLED); 
    Finish (); 

 } 
  } 
}

The interface is still ugly, awkward, you can add functionality based on your needs, the following selection of the directory is basically the same.

Directory Selector

Chooserdialog.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" 
  Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent " > <linearlayout android:orientation= "Horizontal" android:layout_width= "Fill_parent" Android:lay out_height= "40dip" > <button android:layout_width= "40dip" android:layout_height= "40dip" android:t 
  ext= "Home" android:id= "@+id/btn_home" android:layout_gravity= "left" android:layout_weight= "1"/> 
    <linearlayout android:layout_width= "140dip" android:layout_height= "35dip" android:id= "@+id/dir_layout" android:gravity= "Center" android:layout_weight= "1" > </LinearLayout> <!--<textview Andr Oid:layout_width= "140dip" android:layout_height= "35dip" android:id= "@+id/dir_str" android:gravity= "center "Android:layout_weight=" 1 " 
  />--> <button android:layout_width= "40dip" android:layout_height= "40dip" android:text= "B ACK "android:id=" @+id/btn_back "android:layout_gravity=" right "android:layout_weight=" 1 "/> </ linearlayout> <listview android:layout_width= "fill_parent" android:layout_height= "300dip" Android : id= "@+id/list_dir"/> <button android:layout_width= "Fill_parent" android:layout_height= 

 NT "android:id=" @+id/btn_ok "android:text=" OK "/> </LinearLayout>
Package hkp.dirchooser; 
Import Java.io.File; 
Import java.util.ArrayList; 
 
Import java.util.List; 
Import Android.app.Dialog; 
Import Android.content.Context; 
Import Android.os.Bundle; 
Import android.os.Environment; 
Import Android.os.Handler; 
Import android.view.Gravity; 
Import Android.view.View; 
Import Android.widget.AdapterView; 
Import Android.widget.AdapterView.OnItemClickListener; 
Import Android.widget.ArrayAdapter; 
Import Android.widget.Button; 
Import Android.widget.EditText; 
Import Android.widget.LinearLayout; 
Import Android.widget.ListView; 
Import Android.widget.TextView; 
 

Import Android.widget.Toast; 
  public class Dirchooserdialog extends Dialog implements android.view.view.onclicklistener{private ListView list; 
  Arrayadapter<string> Adapter; 
   
  Arraylist<string> arr=new arraylist<string> (); 
  Context context; 
   
  Private String path; 
  Private TextView title; 
  Private EditText et; 
  Private Button Home,back,ok; PrivAte linearlayout Titleview; 
  private int type = 1; 
   
  Private string[] FileType = null; 
  Public final static int typeopen = 1; 
   
  Public final static int typesave = 2; 
   /** * @param context * @param the type value is 1 to create a dialog box that opens the directory type, 2 to create a dialog box to save the file to the directory type * @param fileType the file type to filter, and NULL to select only the directory * @param resultpath dot OK button Returns the result, directory or directory + filename/public dirchooserdialog context,int Type,string[]filetype, 
    String Resultpath) {super (context); 
    TODO auto-generated constructor stub this.context = context; 
    This.type = type; 
    This.filetype = FileType; 
  This.path = Resultpath; }/* (non-javadoc) * @see Android.app.dialog#dismiss () * * * @Override public void Dismiss () {//TODO 
  auto-generated method Stub Super.dismiss (); }/* (non-javadoc) * @see android.app.dialog#oncreate (android.os.Bundle)/@Override protected void ONCR Eate (Bundle savedinstancestate) {//TODO auto-generated Method StUB Super.oncreate (savedinstancestate); 
     
    Setcontentview (R.layout.chooserdialog); 
    Path = Getrootdir (); 
    arr = (arraylist<string>) getdirs (path); Adapter = new Arrayadapter<string> (context,android. 
     
    R.layout.simple_list_item_1, arr); 
    List = (ListView) Findviewbyid (R.id.list_dir); 
     
    List.setadapter (Adapter); 
 
    List.setonitemclicklistener (Lvlis); 
    Home = (Button) Findviewbyid (r.id.btn_home); 
     
    Home.setonclicklistener (this); 
    back = (Button) Findviewbyid (r.id.btn_back); 
     
    Back.setonclicklistener (this); 
    OK = (Button) Findviewbyid (R.ID.BTN_OK); 
     
    Ok.setonclicklistener (this); 
     
    Titleview = (linearlayout) Findviewbyid (r.id.dir_layout); 
      if (type = = Typeopen) {title = new TextView (context); 
      Titleview.addview (title); 
    Title.settext (path); 
      }else if (type = = Typesave) {et = new EditText (context); 
      Et.setwidth (240); 
      Et.setheight (70); Et.Setgravity (Gravity.center); 
      Et.setpadding (0, 2, 0, 0); 
      Titleview.addview (ET); 
    Et.settext ("Wffilename"); 
}//title = (TextView) Findviewbyid (R.ID.DIR_STR); 
     
  Title.settext (path); }///Dynamic update ListView Runnable add=new Runnable () {@Override public void run () {//TODO auto-generate 
D method Stub arr.clear (); 
 
      System.out.println ("Runnable path:" +path); 
      You have to use this method to assign values to arr to update list<string> temp = getdirs (path); 
      for (int i = 0;i < Temp.size (); i++) Arr.add (Temp.get (i)); 
    Adapter.notifydatasetchanged (); 
   
  }     
  }; Private Onitemclicklistener lvlis=new Onitemclicklistener () {@Override public void Onitemclick (adapterview<?& Gt 
arg0, View arg1, int arg2, long arg3) {String temp = (String) arg0.getitematposition (ARG2);       
      System.out.println ("Onitemclick path1:" +path); 
        if (Temp.equals ("..")) 
      Path = Getsubdir (path);else if (path.equals ("/")) path = Path+temp; 
       
else Path = path+ "/" +TEMP;  
      System.out.println ("Onitemclick path2" +path); 
       
      if (type = = Typeopen) title.settext (path); 
      Handler handler=new Handler (); 
    Handler.post (add); 
   
  } 
  }; 
Private list<string> Getdirs (String ipath) {list<string> file = new arraylist<string> ();     
    System.out.println ("Getdirs path:" +ipath); 
    file[] MyFile = new File (ipath). Listfiles (); 
       
    if (MyFile = = null) {File.add (".."); 
          }else for (File f:myfile) {//filter directory if (F.isdirectory ()) {String Tempf = f.tostring (); 
          int pos = Tempf.lastindexof ("/"); 
String subtemp = tempf.substring (pos+1, Tempf.length ()); 
          String subtemp = tempf.substring (Path.length (), tempf.length ());  
File.add (subtemp); 
        System.out.println ("Files in dir:" +subtemp); 
  }//filter known types of files      if (F.isfile () && fileType!= null) {for (int i = 0;i< filetype.length;i++) {int Ty 
             
            Pestrlen = Filetype[i].length (); 
            String fileName = F.getpath (). substring (F.getpath (). Length ()-Typestrlen); if (Filename.tolowercase (). Equals (Filetype[i])) {File.add (f.tostring (). substring (path.length () +1,f.tostrin   
            g (). Length ()); 
     
if (File.size () ==0) File.add (".."); 
    System.out.println ("file[0]:" +file.get (0) + "File size:" +file.size ()); 
  return file; }/* (non-javadoc) * @see Android.view.view.onclicklistener#onclick (android.view.View) * * * * @Override Publi c void OnClick (View v) {//TODO auto-generated Method stub if (v.getid () = = Home.getid ()) {path = Getroot 
      Dir ();       
      if (type = = Typeopen) title.settext (path); 
      Handler handler=new Handler (); 
    Handler.post (add); }eLSE if (V.getid () = = Back.getid ()) {path = Getsubdir (path);       
      if (type = = Typeopen) title.settext (path); 
      Handler handler=new Handler (); 
    Handler.post (add); 
      }else if (v.getid () = = Ok.getid ()) {dismiss (); 
      if (type = = typesave) path = path+ "/" +et.geteditabletext (). toString () + ". WF"; 
    Toast.maketext (context, path, Toast.length_short). Show ();  
      } private String Getsdpath () {File sddir = null; Boolean sdcardexist = Environment.getexternalstoragestate (). Equals (Android.os.Environment.MEDIA_MOUNTE  D); Determine if the SD card exists if (sdcardexist) {sddir = Environment.getexternalstoragedirectory (); 
        /Get root directory} if (Sddir = null) {//toast.maketext (context, "No sdcard inside!", Toast.length_short). Show (); 
      return null;  
       
  return sddir.tostring (); private String Getrootdir () {string ROot = "/"; 
    Path = Getsdpath (); 
     
    if (path = = null) path= "/"; 
  return root; 
     
    private string Getsubdir (string path) {string subpath = null; 
     
    int pos = Path.lastindexof ("/"); 
      if (pos = = Path.length ()) {path = Path.substring (0,path.length ()-1); 
    pos = Path.lastindexof ("/"); 
     
    } subpath = Path.substring (0,pos); 
     
    if (pos = = 0) subpath = path; 
  return subpath; 

 } 
}
Package hkp.dirchooser;

Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.widget.Button; 
 
The public class Mainactivity extends activity {/** called the ' when ' is the ' The activity ' is a 
  -a-created 
  c void OnCreate (Bundle savedinstancestate) { 
    super.oncreate (savedinstancestate); 
    Setcontentview (r.layout.main); 
    Button btn = (button) Findviewbyid (r.id.btn_open); 
    Btn.setonclicklistener (New Onclicklistener () { 
       
      @Override public 
      void OnClick (View v) { 
        //TODO auto-generated method Stub 
        String path = null; 
        String [] FileType = {"DST"};//the list of file types to filter 
        Dirchooserdialog dlg = new Dirchooserdialog (mainactivity.this,2, Filetype,path); 
        Dlg.settitle ("Choose dst file dir"); 
        Dlg.show ();}} 
    ); 
  } 
 


Related Article

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.