一个上传图片的功能,需要对SD中的图片上传:
file_row.xml
directory_list.xml
TestGrid.java
import java.io.File;import java.io.FileFilter;import java.util.ArrayList;import java.util.List;import android.app.ListActivity;import android.os.Bundle;import android.view.KeyEvent;import android.view.View;import android.widget.ListView;public class TestGrid extends ListActivity { private static final FileFilter IMAGES_FILTER = new FileFilter() { public boolean accept(File f) { return f.isDirectory() || f.getName().matches("^.*?\\.(jpg|png|bmp|gif)$"); } }; private FileListAdapter fileList; public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.directory_list); fill(new File("/")); } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && !fileList.isRoot()) { fill(fileList.getItem(1)); return true; } return super.onKeyDown(keyCode, event); } private void fill(File folder) { Listfiles = new ArrayList (); files.add(folder); if (folder.getParentFile() != null) files.add(folder.getParentFile()); for (File file : folder.listFiles(IMAGES_FILTER)) { files.add(file); } fileList = new FileListAdapter(this, R.layout.file_row, files); setListAdapter(fileList); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { File file = fileList.getItem(position); if (file.isDirectory()) fill(file); // TODO use image switcher to display selected images }}
FileListAdapter.java
import java.io.File;import java.util.List;import android.content.Context;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;public class FileListAdapter extends ArrayAdapter{ public FileListAdapter(Context context, int Resource,List objects) { super(context,Resource,objects); // TODO Auto-generated constructor stub } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getView(position, convertView, parent); File file = getItem(position); if (position == 0) view.setText(view.getResources().getString(R.string.current_folder) + file.getAbsolutePath()); else if (position == 1 && !isRoot()) view.setText(R.string.to_parent_folder); else view.setText(file.getName()); return view; } public boolean isRoot() { return getItem(0).getParent() == null; } }