The Simple File Manager implementation method of Android development _android

Source: Internet
Author: User
Tags stub

This article illustrates the simple File Manager implementation approach for Android development. Share to everyone for your reference, specific as follows:

Here using Java I/O, listactivity, Dialog, bitmap and so on to implement a simple File manager, you can view the directory file, modify the file name, delete the file, open the file. Relatively simple, look directly at the code:

Look at the layout file first:

Layout/main.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"
 >
<listview
 android:id= "@android: Id/list
 " Android:layout_width= " Wrap_content "
 android:layout_height=" wrap_content "
 />
</LinearLayout>

File List layout:

Layout/file.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
 android:orientation=" horizontal "
 android:layout_width=" fill_parent "
 android:layout_" height= "Fill_parent"
 >
<imageview
 android:id= "@+id/imageview" android:layout_width= "wrap"
 _content "
 android:layout_height=" wrap_content "
/>
<textview android:id=
 " @+id/textview "
 android:layout_width=" wrap_content "
 android:layout_height=" wrap_content "
 android:textsize=" 14sp ">
</TextView>
</LinearLayout>

Modify File Name dialog box layout file:

Layout/rename_dialog.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
 "http://schemas.android.com/" Apk/res/android "
 android:layout_width=" match_parent "
 android:layout_height=" match_parent ">
 < EditText
  android:id= "@+id/edittext"
  android:layout_width= "Match_parent"
  Wrap_content "
 />
</LinearLayout>

Main activity:

public class Mainactivity extends Listactivity {private static final String Root_path = "/";
 Store file name private arraylist<string> names = null;
 Store file path private arraylist<string> paths = null;
 Private view view;
 Private EditText EditText; /** called the activity is a.
  * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.main);
 Displays a list of files Showfiledir (Root_path);
  private void Showfiledir (String path) {names = new arraylist<string> ();
  paths = new arraylist<string> ();
  File File = new file (path);
  file[] files = file.listfiles (); If the current directory is not a root if (!
   Root_path.equals (PATH)) {Names.add ("@1");
   Paths.add (Root_path);
   Names.add ("@2");
  Paths.add (File.getparent ());
   //Add all files for (file f:files) {Names.add (F.getname ());
  Paths.add (F.getpath ());
 } this.setlistadapter (New Myadapter (This,names, paths)); } @Override protected void onListitemclick (ListView L, View v, int position, long id) {String path = paths.get (position);
  File File = new file (path); The file exists and is readable if (file.exists () && file.canread ()) {if (File.isdirectory ()) {//Display subdirectories and files Showfiledir (path
   );
   else{//Processing files filehandle (file);
   }//No permissions else{Resources res = getresources (); New Alertdialog.builder (this). Settitle (' message '). Setmessage (Res.getstring (r.string.no_permission)).
    Setpositivebutton ("OK", new Onclicklistener () {@Override public void OnClick (Dialoginterface dialog, int which) {
  ). Show ();
 } super.onlistitemclick (L, V, position, id); //Add a deletion to the file private void FileHandle (final file file) {Onclicklistener listener = new Dialoginterface.onclicklistener ( {@Override public void OnClick (Dialoginterface dialog, int which) {//Open file if (which = = 0) {Openfil
    E (file); ///modify filename else if (which = 1) {Layoutinflater factory = LAYOUTINFLAter.from (Mainactivity.this);
     View = Factory.inflate (R.layout.rename_dialog, NULL);
     EditText = (edittext) View.findviewbyid (R.id.edittext);
     Edittext.settext (File.getname ()); Onclicklistener listener2 = new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginterf Ace dialog, int which) {//TODO auto-generated method stub String modifyname = Edittext.gettext (). ToString (
       );
       Final String Fpath = File.getparentfile (). GetPath ();
       Final File newFile = new file (Fpath + "/" + modifyname); if (newfile.exists ()) {//Exclude no modification if (!modifyname.equals (File.getname ())) {New Alertdialog.builde
         R (mainactivity.this). Settitle ("Note!") . Setmessage ("FileName already exists, does it overwrite?") "). Setpositivebutton (" OK ", new Dialoginterface.onclicklistener () {@Override public void OnC Lick (dialoginterface dialog, int which) {if (File.renameto (NewFile)) {ShowfilediR (Fpath); Displaytoast ("Rename succeeded!")
           "); } else{displaytoast (rename failed!)
           ");
          }}). Setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {@Override
        public void OnClick (Dialoginterface dialog, int which) {}}). Show ();
         } else{if (File.renameto (NewFile)) {Showfiledir (Fpath); Displaytoast ("Rename succeeded!")
        "); } else{displaytoast (rename failed!)
        ");
     }
       }
      }
     };
     Alertdialog Renamedialog = new Alertdialog.builder (mainactivity.this). Create ();
     Renamedialog.setview (view);
     Renamedialog.setbutton ("OK", listener2); Renamedialog.setbutton2 ("Cancel", new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginte
     Rface dialog, int which) {//TODO auto-generated Method stub}});
    Renamedialog.show (); ///delete file Else{new Alertdialog.builder (mainactivity.this). Settitle ("Note!") . setmessage (Are you sure you want to delete this file?) "). Setpositivebutton (" OK ", new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialogi
        Nterface dialog, int which) {if (File.delete ()) {//update file list Showfiledir (File.getparent ()); Displaytoast ("Delete succeeded!")
       "); } else{displaytoast (delete failed!)
       "); }}). Setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {@Override public void
    OnClick (dialoginterface dialog, int which) {}}). Show ();
  }
   }
  };
  When you select a file, eject and Delete the Action Options dialog box string[] menu = {"Open file", "rename", "Remove file"};
  New Alertdialog.builder (Mainactivity.this). Settitle ("Please select the action you want to do!") . Setitems (menu, Listener). Setpositivebutton ("Cancel", new Dialoginterface.onclicklistener () {@Override public void O
 Nclick (dialoginterface dialog, int which) {}}). Show (); //Open files private void OpenFile (file file){Intent Intent = new Intent ();
  Intent.addflags (Intent.flag_activity_new_task);
  Intent.setaction (Android.content.Intent.ACTION_VIEW);
  String type = getmimetype (file);
  Intent.setdataandtype (uri.fromfile (file), type);
 StartActivity (Intent);
  //Gets the file MimeType private string getmimetype (file file) {String type = "";
  String name = File.getname ();
  File name extension String end = name.substring (Name.lastindexof (".") + 1, name.length ()). toLowerCase ();
  if (End.equals ("m4a") | | | end.equals ("MP3") | | end.equals ("WAV")) {type = "audio";
  else if (end.equals ("mp4") | | | end.equals ("3gp")) {type = "video"; else if (end.equals ("jpg") | | end.equals ("PNG") | | end.equals ("JPEG") | | end.equals ("BMP") | | end.equals ("GIF")) {T
  ype = "image";
  else {//If it cannot be opened directly, the Jump List is selected by the user type = "*";
  Type = = "/*";
 return type;
 private void Displaytoast (String message) {Toast.maketext (mainactivity.this, message, Toast.length_short). Show ();

 }
}

Custom Adapters:

public class Myadapter extends baseadapter{private layoutinflater inflater;
 Private Bitmap Directory,file;
 Store file name private arraylist<string> names = null;
 Store file path private arraylist<string> paths = null;
  Parameter initialization public Myadapter (context context,arraylist<string> na,arraylist<string> pa) {names = NA;
  paths = PA;
  Directory = Bitmapfactory.decoderesource (Context.getresources (), R.DRAWABLE.D);
  File = Bitmapfactory.decoderesource (Context.getresources (), R.DRAWABLE.F);
  Shrink Picture directory = Small (directory,0.16f);
  File = Small (file,0.1f);
 Inflater = Layoutinflater.from (context);
 @Override public int GetCount () {//TODO auto-generated a stub return names.size ();
 @Override public Object getitem (int position) {//TODO auto-generated Method stub return Names.get (position);
 @Override public long getitemid (int position) {//TODO auto-generated method stub return position; @Override public View getview (int positioN, View Convertview, ViewGroup parent) {//TODO auto-generated method stub viewholder holder;
   if (null = = Convertview) {Convertview = inflater.inflate (r.layout.file, NULL);
   Holder = new Viewholder ();
   Holder.text = (TextView) Convertview.findviewbyid (R.id.textview);
   Holder.image = (ImageView) Convertview.findviewbyid (R.id.imageview);
  Convertview.settag (holder);
  else {holder = (Viewholder) convertview.gettag ();
  File F = new file (paths.get (position). ToString ());
   if (Names.get (position). Equals ("@1")) {Holder.text.setText ("/");
  Holder.image.setImageBitmap (directory);
   else if (names.get (position). Equals ("@2")) {Holder.text.setText ("..");
  Holder.image.setImageBitmap (directory);
   } else{Holder.text.setText (F.getname ());
   if (F.isdirectory ()) {holder.image.setImageBitmap (directory);
   else if (F.isfile ()) {holder.image.setImageBitmap (file);
   } else{System.out.println (F.getname ()); } return CONVERTVIew
  Private class viewholder{private TextView text;
 Private ImageView image;
  Private Bitmap Small (Bitmap map,float num) {Matrix matrix = new Matrix ();
  Matrix.postscale (num, num);
 Return Bitmap.createbitmap (Map,0,0,map.getwidth (), Map.getheight (), matrix,true);

 }
}

Because you want to manipulate the file, authorize it in the description file:

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android=
"http://schemas.android.com/apk/res/" Android "
  package=" Com.test.filemanager "
  android:versioncode=" 1 "
  android:versionname=" 1.0 ">
 <uses-sdk android:minsdkversion= "/>
 <strong> <uses-permission android:name=" Android.permission.MOUNT_UNMOUNT_FILESYSTEMS "/>
 <uses-permission android:name=" Android.permission.WRITE_EXTERNAL_STORAGE "/></strong>
 <application android:icon=" @drawable/icon "Android:label=" @string/app_name ">
  <activity android:name=". Mainactivity "
     android:label=" @string/app_name ">
   <intent-filter>
    <action android:name = "Android.intent.action.MAIN"/>
    <category android:name= "Android.intent.category.LAUNCHER"/>
   </intent-filter>
  </activity>
 </application>
</manifest>

The results of the operation are as follows:

View catalog Files

File Rename:

To delete a file:

Open File:

I hope this article will help you with the Android program.

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.