Android 编程之入门开发文件夹管理器开发详细讲解-1

在我们的手持设备中,一般都会自带设备公司自己开发的文件管理系统、拍照系统之类的东东,今天我给大伙说说入门级开发的文件夹管理器,代码贼少

总共就6个类吧,没有夹杂其他外部应用,就是一个纯文件夹管理器

APP主要功能设计:文件复制、文件夹复制、批量文件/文件夹复制、删除文件、删除文件夹、批量删除文件/文件夹、文件分类、文件搜索暂时没有写,

有兴趣的可以自己写写

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

下面开始讲开发吧,首先我们要给APP读写权限,在清单文件配置如下权限:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

主界面活动代码:

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<Map<String, Object>> draweralllist = new ArrayList<Map<String, Object>>();
	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<String, Object> drawer_list_date = new HashMap<String, Object>();
			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<fragmentA.filelist.size();i++){
//				if(fragmentA.filelist.get(i).exists()){
//					new AlertDialog.Builder(this)
//					.setTitle("复制提示")
//					.setMessage("已存在文件"+fragmentA.filelist.get(i).getName())
//					.setPositiveButton("覆盖", new OnClickListener() {
//						public void onClick(DialogInterface dialog, int which) {
//						}
//					})
//					.setNegativeButton("取消", null)  
//	                .show();
					opreaFile.copyDirectory(fragmentA.filelist.get(i), currentpath);
//				}
				}
			fragmentA.filelist.clear();
			fragmentA.openFile(currentpath);
			Log.d("Paete-XXXXXXXXXXX", "xxxxxxxxxxxx");
			fragmentA.showMessage("执行粘贴");
		break;
		case R.id.action_menu_new:
			View view=LayoutInflater.from(this).inflate(R.layout.list_item, null);
			newFile=(EditText)view.findViewById(R.id.newFile);
			new AlertDialog.Builder(this)
			.setTitle("新建文件")
			.setView(view)
			.setPositiveButton("确定", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					String newfile=
							"/"+fragmentA.showpath.getText().toString()+"/"
							+newFile.getText().toString()+"/";
					File newfile2=new File(newfile);
					Log.d("***********", newfile);
					if(!newfile2.exists()){  
						newfile2.mkdirs();
					}
					fragmentA.filelist.clear();
					fragmentA.openFile(currentpath);
					fragmentA.showMessage("执行新建");
				} 
			})
			.setNegativeButton("取消", null)  
            .show();
			break;
		case R.id.action_menu_search:
			
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	public void onItemClick(AdapterView<?> 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<File> filelist=new ArrayList<File>();
		
		//下段注释代码表示往Map里面添加文件数据,如果filename为文件夹,则设置为图标icon[1],否则设置icon[0]
		//private int[] icon = { R.drawable.wenjian, R.drawable.wenjianjia };
		//Map<String,Object> map=new HaspMap<String,Object>();
		//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<array.size();i++){
					if(array.valueAt(i)==true){
						int x=array.keyAt(i);
						filelist.add(mfileData[x]);
					}
				}
				Log.d("Copy-XXXXXXXXXXX", "xxxxxxxxxxxx");
				mode.finish();
//				showMessage(""+"复制");
				break;
//			case R.id.paste:
//				copy=false;
//				Paste();
//				for(int i=0;i<filelist.size();i++){
//					opreaFile.copyDirectory(filelist.get(i), currentpath);
//				}
//				filelist.clear();
//				openFile(currentpath);
//				Log.d("Paete-XXXXXXXXXXX", "xxxxxxxxxxxx");
//				showMessage("执行粘贴");
//				mode.finish();
////				showMessage(""+"粘贴");
//				break;
			default:
				break;
			}
			return true;
		}
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			getActivity().getMenuInflater().inflate(R.menu.action_menu, menu);
//			mode.setTitle("你選擇了");
			return true;
		}
		public void onDestroyActionMode(ActionMode arg0) {
		}
		public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
			return false; 
		}
		public void onItemCheckedStateChanged(ActionMode mode, int position,
				long id, boolean checked) {
			int count = listview.getCheckedItemCount();
			mode.setTitle(count + "项");
		}  
		public void onItemClick(AdapterView<?> 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<String, Integer, Integer>{

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

主布局:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/chouti"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <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"
        />
    <ListView 
        android:id="@+id/drawer_list"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#eee"
        />

</android.support.v4.widget.DrawerLayout>


文件列表 Item 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/drawer_bg"
    >

    <ImageView
        android:id="@+id/filelist_imageview"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="10dp"
        android:src="@drawable/photos"
        />

    <TextView
        android:id="@+id/filelist_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="17dp"
        android:layout_toRightOf="@+id/filelist_imageview"
        android:gravity="center_vertical"
        android:text="showfiletext" />

    <TextView
        android:id="@+id/filelist_timeText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/filelist_textview"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/filelist_textview"
        android:text="time" />

</RelativeLayout>

自定义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内存为空,请自行新建文件测试,谢谢~

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。