Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 編程之入門開發文件夾管理器開發詳細講解-1

Android 編程之入門開發文件夾管理器開發詳細講解-1

編輯:關於Android編程

在我們的手持設備中,一般都會自帶設備公司自己開發的文件管理系統、拍照系統之類的東東,今天我給大伙說說入門級開發的文件夾管理器,代碼贼少

總共就6個類吧,沒有夾雜其他外部應用,就是一個純文件夾管理器

APP主要功能設計:文件復制、文件夾復制、批量文件/文件夾復制、刪除文件、刪除文件夾、批量刪除文件/文件夾、文件分類、文件搜索暫時沒有寫,

有興趣的可以自己寫寫

APP主要應用:DrawerLayout 、ListView、Fragment、IO、序列化、文件過濾、文件排序、ActionBar、Adapter、v4包、一些事件等

下面開始講開發吧,首先我們要給APP讀寫權限,在清單文件配置如下權限:

    
    

主界面活動代碼:

package com.example.maozhuafile;
/**
 * 文件管理主界面
 * @author Engineer-Jsp
 * @date 2014.10.27
 * */
import java.io.File; 
import java.util.ArrayList;
import java.util.HashMap;  
import java.util.List;
import java.util.Map; 
import com.example.maozhuafile.MainActivity.FragmentA.FragmentB;
import com.example.maozhuafile.MainActivity.FragmentA.FragmentC;
import com.example.maozhuafile.MainActivity.FragmentA.FragmentD;
import com.example.util.CustomFileFilter;
import com.example.util.FileOpreationUitl;
import com.example.util.FileSort;
import com.example.util.FragmentAdapter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemClickListener {
	private ActionBar actionbar;
	private ActionBarDrawerToggle drawertoggle;
	private DrawerLayout drawerLayout;
	private ListView drawerlistview;
	private String[] drawerdata;
	private SimpleAdapter adapter;
	private List> draweralllist = new ArrayList>();
	private FragmentA fragmentA;
	private FragmentB fragmentB;
	private FragmentC fragmentC;  
	private FragmentD fragmentD;
	private int[] list_image = { R.drawable.cunchu, R.drawable.music,
			R.drawable.movies, R.drawable.photos };
	private static int index = -1;
	private static File currentpath;
	private static File SDpath;
//	private static File[] mfileData;
	private static Context mContext;
	public  static boolean exit;
	private static boolean copy;
	private static MenuItem paste;
	int i=0;
	private static EditText newFile;
	private static FileOpreationUitl opreaFile=new FileOpreationUitl();
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = MainActivity.this;
		initDrawerLayout();
		//
		initDrawerContent();
		//
		if (null == savedInstanceState) {
			// 如果為空代表第一次執行
			fragmentA = new FragmentA();
			fragmentB = new FragmentB();
			fragmentC = new FragmentC();
			fragmentD = new FragmentD();
			// 動態添加
			android.app.FragmentManager fg = getFragmentManager();
			fg.beginTransaction().add(R.id.drawer_frame_a, fragmentA).commit();
		}
	}
	private void initDrawerContent() {
		drawerdata = getResources().getStringArray(R.array.array);
		drawerlistview = (ListView) findViewById(R.id.drawer_list);
		for (int i = 0; i < drawerdata.length; i++) {
			Map drawer_list_date = new HashMap();
			drawer_list_date.put("image", list_image[i]);
			drawer_list_date.put("text", drawerdata[i]);
			draweralllist.add(drawer_list_date);
		}
		adapter = new SimpleAdapter(this, draweralllist, R.layout.drawer_item,
				new String[] { "image", "text" }, new int[] {
						R.id.drawer_imageView, R.id.drawer_textView });
		drawerlistview.setAdapter(adapter);
		drawerlistview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);// 單選模式
		drawerlistview.setItemChecked(0, true);// 默認選中第一項
		drawerlistview.setOnItemClickListener(this);
	}
	private void initDrawerLayout() {
		drawerLayout = (DrawerLayout) findViewById(R.id.chouti);
		actionbar = getActionBar();
		actionbar.setDisplayHomeAsUpEnabled(true);
		drawertoggle = new ActionBarDrawerToggle(this,// 活動
				drawerLayout,// 布局
				R.drawable.ic_drawer,// 圖片資源
				R.string.drawer_open,// 打開顯示文字
				R.string.app_name) {// 關閉顯示文字
			public void onDrawerOpened(View drawerView) {
				actionbar.setTitle(R.string.drawer_open);
				if (index != -1) {
					actionbar.setTitle(drawerdata[index]);
				} else {
					actionbar.setTitle(R.string.app_name);
				}
				invalidateOptionsMenu();// 選項菜單重繪改變
				super.onDrawerOpened(drawerView);
			}
			public void onDrawerClosed(View drawerView) {
				if (index != -1) {
					actionbar.setTitle(drawerdata[index]);
				} else {
					actionbar.setTitle(R.string.app_name);
				}
				invalidateOptionsMenu();// 選項菜單重繪改變
				super.onDrawerClosed(drawerView);
			}
		};
		drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
		drawerLayout.setDrawerListener(drawertoggle);
	}
	// 替換抽屜開關上的圖片(向上箭頭三道槓)
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		drawertoggle.syncState();
	}
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		paste=menu.findItem(R.id.paste);
		return true;
	}
	// 選項菜單的預處理方法重寫
	public boolean onPrepareOptionsMenu(Menu menu) {
		// 如果抽屜被打開
		if (drawerLayout.isDrawerOpen(Gravity.START)) {
			// 找到這個AcionBarMenu(操作欄菜單)Item把可見性顯示為false(即顯示為不可見)
			menu.findItem(R.id.action_menu_new).setVisible(false);
		}
		return super.onPrepareOptionsMenu(menu);
	}
	public boolean onOptionsItemSelected(MenuItem item) {
		// 抽屜開關控制Open,Off
		if (drawertoggle.onOptionsItemSelected(item)) {
			return true;
		}
		switch(item.getItemId()){
		case R.id.paste:
			copy=false;
			fragmentA.Paste();
			for(;i parent, View view, int position,
			long id) {
		drawerLayout.closeDrawer(Gravity.START);
		//更新ActionBar(操作欄)的標題
					actionbar.setTitle(drawerdata[position]);
					index=position;
					//抽屜列表按鈕
					switch (position) {
					case 0:
						getFragmentManager().beginTransaction().replace(R.id.drawer_frame_a, fragmentA).commit();
						break;
			        case 1:
						getFragmentManager().beginTransaction().replace(R.id.drawer_frame_a, fragmentB).commit();
						break;
			        case 2:
			        	getFragmentManager().beginTransaction().replace(R.id.drawer_frame_a, fragmentC).commit();
				        break;
			        case 3:
			        	getFragmentManager().beginTransaction().replace(R.id.drawer_frame_a, fragmentD).commit();
				        break;
					default:
						break;
					}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK){
			if(currentpath.equals(SDpath)){
				if(!exit){//exit==false
					fragmentA.showMessage("在點返回則退出程序!");
					exit=true;
				}else{
					finish();
				}
			}else{
				exit=false;  
				File path=currentpath.getParentFile();
				fragmentA.openFile(path);
				fragmentA.showpath.setText(String.valueOf(path));
				fragmentA.adapter.notifyDataSetChanged();
			}
			return true;  
			}
		return super.onKeyDown(keyCode, event);
		}
	public static class FragmentA extends Fragment implements
			MultiChoiceModeListener, OnItemClickListener {
		public static TextView showpath;
		private ListView listview;
		private FragmentAdapter adapter;
//		private File[] files;
		private File[] mfileData;
		int n;
		private List filelist=new ArrayList();
		
		//下段注釋代碼表示往Map裡面添加文件數據,如果filename為文件夾,則設置為圖標icon[1],否則設置icon[0]
		//private int[] icon = { R.drawable.wenjian, R.drawable.wenjianjia };
		//Map map=new HaspMap();
		//map.put("keyname",filename.isDirectory?icon[1]:icon[0]);
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			Log.d("onCreateView.........", "onCreateView.........");
			View view  = inflater.inflate(R.layout.fragment_a, container, false);
			showpath=(TextView)view.findViewById(R.id.showpath);
			listview = (ListView) view.findViewById(R.id.listView);
			//
//			if (mfileData == null) {
//				SDpath = Environment.getExternalStorageDirectory();
//				showpath.setText(String.valueOf(SDpath));
//				 mfileData = SDpath.listFiles(new CustomFileFilter()); // 過濾.文件
//				 mfileData = FileSort.sortFile(mfileData);//排序
//				 openFile(SDpath);
//			}
			//
			bindData();  
			return view;
		}
		// 綁定數據
		public void bindData() { 
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) { 
				// 判斷sd卡是否正常
				if (mfileData == null) {
					SDpath = Environment.getExternalStorageDirectory();
					showpath.setText(String.valueOf(SDpath));
					getFileData();
				}
				//判斷文件夾數據組是否取到了數據
				for (int i = 0; i < mfileData.length; i++) {
					Log.i("float1", "111111" + mfileData[i] + "");
				}
			} else {
				showMessage("SD卡出現異常");
			}
		}
		private File[] getFileData() {
		    mfileData = SDpath.listFiles(new CustomFileFilter()); // 過濾.文件
			mfileData = FileSort.sortFile(mfileData);//排序
			openFile(SDpath);
			return mfileData;
		}
		public void Paste() {
			if (copy) {
				paste.setVisible(true);
				paste.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			} else {
				paste.setVisible(false);
				paste.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
			}
		}
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			SparseBooleanArray array = listview.getCheckedItemPositions();
			switch (item.getItemId()) {
//			case R.id.newfile:
//		 q		showMessage(""+"新建");
//				break;
//			case R.id.search:
//				showMessage(""+"搜索");
//				break;
			case R.id.remove:
				//這處理下面這個稀疏數組時盡量不要使用靜方法態調用和靜態變量
				//靜態不能再次調用靜態,否則報異常
				for (int i = 0; i < array.size(); i++) {
					Log.d("del-4XXXXXXXXXXX", mfileData[array.keyAt(i)].getName().toString());
					if(array.valueAt(i)==true){
						 n= array.keyAt(i);
						opreaFile.deleteFile(mfileData[n]);
					}
					Log.d("del-XXXXXXXXXXX", currentpath.listFiles().toString());
					Log.d("del-XXXXXXXXXXX", currentpath.getName().toString());
					Log.d("del-XXXXXXXXXXX", showpath.getText().toString());
				}  
				openFile(currentpath);
				showMessage("刪除成功");
//				showMessage("刪除"+mfileData[array.keyAt(n)].isFile()?"刪除文件成功!":"刪除文件夾成功!");
				mode.finish();
			case R.id.copy:
				copy=true;
				Paste();
				//屏蔽復制按鈕
//				mode.getMenu().findItem(R.id.copy).setVisible(false);
//				//顯示粘貼按鈕
//				mode.getMenu().findItem(R.id.paste).setVisible(true);
				for(int i=0;i parent, View view, int position,
				long id) {
			File file = mfileData[position];
			showpath.setText(String.valueOf(file)); 
			Log.d("onItem-xxxxxxxxxxxxxx", showpath.getText().toString());
			if(file.isDirectory()){
				openFile(file);
				adapter.notifyDataSetChanged();
			}else{
				//打開文件
				Uri uri = Uri.fromFile(file);
				Log.d("aaaaaaaaaaaaaa", uri.toString());
				String[] projection = { MediaStore.Files.FileColumns.MIME_TYPE };
				Cursor cursor = getActivity().getContentResolver().query(
						MediaStore.Files.getContentUri("external"), projection,
						MediaStore.Files.FileColumns.DATA + "=?",
						new String[] { file.getAbsoluteFile().toString() },
						null);
				cursor.moveToNext();
				String mime = cursor.getString(0);
				Log.d("bbbbbbbbbbbbbb", mime);
				// MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(uri, mime);
				getActivity().startActivity(intent);
			} 
		}
		public void openFile(File path) {
			currentpath=path;
						mfileData = path.listFiles(new CustomFileFilter()); // 過濾.文件
						mfileData= FileSort.sortFile(mfileData); // 排序
						adapter = new FragmentAdapter(mfileData,
								getActivity());
						listview.setAdapter(adapter);
						for (int i = 0; i < mfileData.length; i++) {
							Log.i("XXXXXXXXXXXX", "111111111111" + mfileData[i] + "");
						}
//						showMessage("當前文件夾有"+mfileData.length+"個對象");
						listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); 
						listview.setMultiChoiceModeListener(FragmentA.this);
						listview.setOnItemClickListener(this);
		}
		public void showMessage(String info) {
			Toast.makeText(mContext, info, 1000).show();  
		}
	public static class FragmentB extends Fragment {
		private ListView mp3list;
		private SimpleAdapter mp3adapter;
		public View onCreateView(LayoutInflater inflater,
		ViewGroup container,
		Bundle savedInstanceState) {
			View view = inflater.inflate
			(R.layout.fragment_b, container, false);
			mp3list=(ListView)view.findViewById(R.id.mp3listView);
			opreaFile.getReciver(SDpath);
			
			mp3adapter=new SimpleAdapter(getActivity(),
					opreaFile.mp3_data,
					R.layout.mp3_fragment_b,
					new String[]{opreaFile.mp3_listitem},
					new int[]{R.id.mp3textView});
			mp3list.setAdapter(mp3adapter);
			return view;
		}  
	}
	public static class FragmentC extends Fragment {
		private ListView video_list;
		private SimpleAdapter video_adapter;
		public View onCreateView(LayoutInflater inflater,
		ViewGroup container,
		Bundle savedInstanceState) {
			View view = inflater.inflate
			(R.layout.fragment_c, container, false);
			video_list=(ListView)view.findViewById(R.id.video_listView);
			Log.d("2_XXXXXXXXXX", SDpath.getName().toString());
			opreaFile.getVideo(SDpath);
			
			video_adapter=new SimpleAdapter(getActivity(),
					opreaFile.video_data,
					R.layout.video_fragment_b,
					new String[]{opreaFile.video_listitem},
					new int[]{R.id.video_textView});
			video_list.setAdapter(video_adapter);
			return view;
		}
	}
	public static class FragmentD extends Fragment {
		private ListView picture_list;
		private SimpleAdapter picture_adapter; 
		public View onCreateView(LayoutInflater inflater,
		ViewGroup container,
		Bundle savedInstanceState) {
			View view = inflater.inflate  
			(R.layout.fragment_d, container, false);
			picture_list=(ListView)view.findViewById(R.id.picture_listView);
			opreaFile.getPicture(SDpath);
			picture_adapter=new SimpleAdapter(getActivity(),
					opreaFile.picture_data,
					R.layout.picture_fragment_b,
					new String[]{opreaFile.picture_listitem}, 
					new int[]{R.id.picture_textView});
			picture_list.setAdapter(picture_adapter);  
			return view;  
		}
	}  
}
/*	public static class AsyncTaskTest extends AsyncTask{

		@Override
		protected Result doInBackground(Params... arg0) {
			
			return null;
		}
		
	}*/
}

主布局:


    <frameLayout 
        android:id="@+id/drawer_frame_a"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
    <frameLayout 
        android:id="@+id/drawer_frame_b"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
    



文件列表 Item 布局文件:




    

    

    



自定義Adapter,控制文件與應用圖片配對,隊號入座,ViewHolder 節約內存資源:

package com.example.util;
/**
 * 自定義容器Adapter
 * @author Engineer-Jsp
 * @date 2014.10.27
 * */
import java.io.File;
import java.util.Date;
import com.example.maozhuafile.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class FragmentAdapter extends BaseAdapter {

    private Context mContext ;	 
    private File[] mfileData ;
	private LayoutInflater mlayoutinflater;


	public FragmentAdapter( File[]files ,Context pContext) {
		mContext = pContext ;
		mfileData = files ;
		mlayoutinflater = LayoutInflater.from(mContext);
	}
	
	public  void updata(File[] pfile){
		mfileData = pfile ;
	}

	public int getCount() {
	  return mfileData ==null? 0: mfileData.length;
	}

	public Object getItem(int position) {
	
		return mfileData[position];
	}

	public long getItemId(int position) {
		return position;
	}

	public static  class ViewHolder{
		public ImageView mFileImage ;
		public TextView mFileName ;
		public TextView mFileTime;
	}
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder mViewHolder ;
		View _view = convertView ;
		if(_view ==null){
			
			mViewHolder = new ViewHolder() ;
			_view = mlayoutinflater.inflate(R.layout.file_listview, null) ;
			mViewHolder.mFileImage =(ImageView) _view.findViewById(R.id.filelist_imageview
					) ;
			mViewHolder.mFileName = (TextView) _view.findViewById(R.id.filelist_textview) ;
			mViewHolder.mFileTime = (TextView) _view.findViewById(R.id.filelist_timeText);
			_view.setTag(mViewHolder) ;
		}else{
			mViewHolder = (ViewHolder) _view.getTag() ;
		}
		
//		目錄的顯示特點
		if(mfileData[position].isDirectory() && mfileData[position].canRead()){  
//			文件夾分為空與非空
			if(mfileData[position].listFiles().length == 0 && mfileData[position].listFiles()== null  ){
				mViewHolder.mFileImage.setImageResource(R.drawable.wenjian) ;
				mViewHolder.mFileName.setText(mfileData[position].getName()) ;
				mViewHolder.mFileTime.setText(new Date(System.currentTimeMillis()).toLocaleString());
			}else{
				mViewHolder.mFileImage.setImageResource(R.drawable.wenjianjia) ;
				mViewHolder.mFileName.setText(mfileData[position].getName()) ;
				mViewHolder.mFileTime.setText(new Date(System.currentTimeMillis()).toLocaleString());
			}
			
		 }else{   //文件的處理
			 
			 String _FileName = mfileData[position].getName().toLowerCase() ;
			 
			 if(_FileName.endsWith(".txt")){  //文本顯示t
                  mViewHolder.mFileImage.setImageResource(R.drawable.wenjian) ;
				  mViewHolder.mFileName.setText(_FileName) ; 
				  mViewHolder.mFileTime.setText(new Date(System.currentTimeMillis()).toLocaleString());
					  
			 }else if(_FileName.endsWith(".png") || _FileName.endsWith(".jpg") ||_FileName.endsWith(".jpeg") || _FileName.endsWith(".gif")){
				 mViewHolder.mFileImage.setTag(mfileData[position].getAbsolutePath()) ;
				 mViewHolder.mFileImage.setImageResource(R.drawable.ic_action_picture);
				 mViewHolder.mFileName.setText(_FileName) ;  
				 mViewHolder.mFileTime.setText(new Date(System.currentTimeMillis()).toLocaleString());
				 
			 }else if(_FileName.endsWith(".mp4")|| _FileName.endsWith(".avi")|| _FileName.endsWith(".3gp") || _FileName.endsWith(".rmvb")){
				  mViewHolder.mFileImage.setImageResource(R.drawable.ic_action_video) ;
				  mViewHolder.mFileName.setText(_FileName) ; 
				  mViewHolder.mFileTime.setText(new Date(System.currentTimeMillis()).toLocaleString());
				  
			 }else if(_FileName.endsWith("mp3")){
				  mViewHolder.mFileImage.setImageResource(R.drawable.mp3) ;
				  mViewHolder.mFileName.setText(mfileData[position].getName()) ; 
				  mViewHolder.mFileTime.setText(new Date(System.currentTimeMillis()).toLocaleString());
			 }else if(_FileName.endsWith("doc")){
				 mViewHolder.mFileImage.setImageResource(R.drawable.word) ;
				 mViewHolder.mFileName.setText(mfileData[position].getName()) ; 
				 mViewHolder.mFileTime.setText(new Date(System.currentTimeMillis()).toLocaleString());
			 }
					 
		}
		
	/*	View view = convertView ;
		view =mlayoutinflater.inflate(com.example.jsp.R.layout.list_item, null) ;
		TextView tv = (TextView)view.findViewById(com.example.jsp.R.id.tv_name1) ;
		tv.setText(mfileData[position].getName()+"") ;*/
		
		return _view;
		
	}
//	public static void main(String[] args) {
//		System.out.println(new Date(System.currentTimeMillis()).toString());
//	}
}


至此主活動布局就完成了,主布局效果圖:


注意:如果使用模擬器測試,請注意,如果模擬器沒有開啟 SD 內存iso,請自行開啟測試,如果SD內存為空,請自行新建文件測試,謝謝~

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