Android開發(fā)之簡單文件管理器實現(xiàn)方法
本文實例講述了Android開發(fā)之簡單文件管理器實現(xiàn)方法。分享給大家供大家參考,具體如下:
這里運用Java I/O、ListActivity、Dialog、Bitmap等實現(xiàn)簡單文件管理器,可以查看目錄文件,修改文件名,刪除文件,打開文件。比較簡單,直接看代碼:
先看布局文件:
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>
文件列表布局:
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>
修改文件名對話框布局文件:
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" android:layout_height="wrap_content" /> </LinearLayout>
主Activity:
public class MainActivity extends ListActivity { private static final String ROOT_PATH = "/"; //存儲文件名稱 private ArrayList<String> names = null; //存儲文件路徑 private ArrayList<String> paths = null; private View view; private EditText editText; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //顯示文件列表 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(); //如果當(dāng)前目錄不是根目錄 if (!ROOT_PATH.equals(path)){ names.add("@1"); paths.add(ROOT_PATH); names.add("@2"); paths.add(file.getParent()); } //添加所有文件 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); // 文件存在并可讀 if (file.exists() && file.canRead()){ if (file.isDirectory()){ //顯示子目錄及文件 showFileDir(path); } else{ //處理文件 fileHandle(file); } } //沒有權(quán)限 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); } //對文件進(jìn)行增刪改 private void fileHandle(final File file){ OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 打開文件 if (which == 0){ openFile(file); } //修改文件名 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(DialogInterface 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()){ //排除沒有修改情況 if (!modifyName.equals(file.getName())){ new AlertDialog.Builder(MainActivity.this) .setTitle("注意!") .setMessage("文件名已存在,是否覆蓋?") .setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (file.renameTo(newFile)){ showFileDir(fpath); displayToast("重命名成功!"); } else{ displayToast("重命名失?。?); } } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } } else{ if (file.renameTo(newFile)){ showFileDir(fpath); displayToast("重命名成功!"); } else{ displayToast("重命名失敗!"); } } } }; AlertDialog renameDialog = new AlertDialog.Builder(MainActivity.this).create(); renameDialog.setView(view); renameDialog.setButton("確定", listener2); renameDialog.setButton2("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); renameDialog.show(); } //刪除文件 else{ new AlertDialog.Builder(MainActivity.this) .setTitle("注意!") .setMessage("確定要刪除此文件嗎?") .setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(file.delete()){ //更新文件列表 showFileDir(file.getParent()); displayToast("刪除成功!"); } else{ displayToast("刪除失敗!"); } } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } } }; //選擇文件時,彈出增刪該操作選項對話框 String[] menu = {"打開文件","重命名","刪除文件"}; new AlertDialog.Builder(MainActivity.this) .setTitle("請選擇要進(jìn)行的操作!") .setItems(menu, listener) .setPositiveButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } //打開文件 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); } //獲取文件mimetype private String getMIMEType(File file){ String type = ""; String name = file.getName(); //文件擴展名 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")){ type = "image"; } else { //如果無法直接打開,跳出列表由用戶選擇 type = "*"; } type += "/*"; return type; } private void displayToast(String message){ Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show(); } }
自定義適配器:
public class MyAdapter extends BaseAdapter{ private LayoutInflater inflater; private Bitmap directory,file; //存儲文件名稱 private ArrayList<String> names = null; //存儲文件路徑 private ArrayList<String> paths = null; //參數(shù)初始化 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); //縮小圖片 directory = small(directory,0.16f); file = small(file,0.1f); inflater = LayoutInflater.from(context); } @Override public int getCount() { // TODO Auto-generated method 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); } }
因為要對文件進(jìn)行操作,所以在描述文件中授權(quán):
<?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="10" /> <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>
運行結(jié)果如下:
查看目錄文件
文件重命名:
刪除文件:
打開文件:
希望本文所述對大家Android程序設(shè)計有所幫助。
相關(guān)文章
Android官方的側(cè)滑控件DrawerLayout的示例代碼
這篇文章主要介紹了Android官方的側(cè)滑控件DrawerLayout的示例代碼,非常具有實用價值,需要的朋友可以參考下2017-09-09淺談Android開發(fā)Webview的Loading使用效果
這篇文章主要為大家介紹了淺談Android開發(fā)Webview的Loading使用效果詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02android 監(jiān)聽網(wǎng)絡(luò)狀態(tài)的變化及實戰(zhàn)的示例代碼
本篇文章主要介紹了android 監(jiān)聽網(wǎng)絡(luò)狀態(tài)的變化及實戰(zhàn)的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01Android自定義ViewGroup之實現(xiàn)FlowLayout流式布局
這篇文章主要為大家詳細(xì)介紹了Android自定義ViewGroup之實現(xiàn)FlowLayout流式布局的相關(guān)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-06-06android getActivity.findViewById獲取ListView 返回NULL的方法
下面小編就為大家?guī)硪黄猘ndroid getActivity.findViewById獲取ListView 返回NULL的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11Android TextView(圓?。┻吙蚝捅尘皩嵗斀?/a>
這篇文章主要介紹了 Android TextView(圓?。┻吙蚝捅尘皩嵗斀獾南嚓P(guān)資料,這里提供了實現(xiàn)代碼和實現(xiàn)效果圖,需要的朋友可以參考下2016-11-11Android對圖片Drawable實現(xiàn)變色示例代碼
這篇文章主要給大家介紹了關(guān)于Android對圖片Drawable實現(xiàn)變色的相關(guān)資料,文中通過示例代碼將實現(xiàn)的方法介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧。2017-08-08