您的位置:首页 > 移动开发 > Android开发

Android 的ListView操作实例,文件管理器SD卡的读取操作

2014-03-26 22:10 435 查看
文件管理器SD卡:

实现效果:



点击后的效果:





下面来具体实现步骤:

文件管理器显示样式,来设置布局。

创建项目对Androidmanifest修改:



一、编写activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/title_text"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:text="当前位置: /mnt/sdcard"
        android:textSize="14sp" />

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="8"
        android:cacheColorHint="#00000000" >
    </ListView>

</LinearLayout>

显示的样式:



编写file_line.xml完成单行数据处理:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/file_img"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/file_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="4"
        android:textSize="14sp" />

</LinearLayout>

将用到的图片拷贝到项目中,并准备编写自定义的Adapter。

但这里的图片大小有可能有问题,因此需要编写一个Globals来计算总屏幕宽度和高度。

public class Globals {

	public static int SCREEN_WIDTH;
	public static int SCREEN_HEIGHT;
	// 建立一个Map集合, 里面封装了所有扩展名对应的图标图片, 以便进行文件图标的显示
	public static Map<String, Integer> allIconImgs = new HashMap<String, Integer>();

	public static void init(Activity a) {
		SCREEN_WIDTH = a.getWindowManager().getDefaultDisplay().getWidth();
		SCREEN_HEIGHT = a.getWindowManager().getDefaultDisplay().getHeight();

		// 初始化所有扩展名和图片的对应关系
		allIconImgs.put("txt", R.drawable.txt_file);
		allIconImgs.put("mp3", R.drawable.mp3_file);
		allIconImgs.put("mp4", R.drawable.mp4_file);
		allIconImgs.put("bmp", R.drawable.image_file);
		allIconImgs.put("gif", R.drawable.image_file);
		allIconImgs.put("png", R.drawable.image_file);
		allIconImgs.put("jpg", R.drawable.image_file);
		allIconImgs.put("dir_open", R.drawable.open_dir);
		allIconImgs.put("dir_close", R.drawable.close_dir);
	}
}

三、建立Adapter

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.liky.file.R;
import org.liky.file.util.Globals;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class FileAdapter extends BaseAdapter {

	private Context ctx;
	private List<Map<String, Object>> allValues = new ArrayList<Map<String, Object>>();

	public FileAdapter(Context ctx, List<Map<String, Object>> allValues) {
		this.ctx = ctx;
		this.allValues = allValues;
	}

	@Override
	public int getCount() {
		return allValues.size();
	}

	@Override
	public Object getItem(int arg0) {
		return allValues.get(arg0);
	}

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

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = LayoutInflater.from(ctx).inflate(R.layout.file_line,
					null);
			// 设置高度
			convertView.setLayoutParams(new LayoutParams(
					LayoutParams.MATCH_PARENT, Globals.SCREEN_HEIGHT / 9));
		}

		// 取得组件
		TextView fileImg = (TextView) convertView.findViewById(R.id.file_img);

		fileImg.getLayoutParams().height = Globals.SCREEN_HEIGHT / 9;

		TextView fileName = (TextView) convertView.findViewById(R.id.file_name);

		// 取得数据,设置到组件里
		Map<String, Object> map = allValues.get(position);

		// 设置内容, 文字
		fileName.setText(map.get("fileName").toString());

		// 图片要根据扩展名取得
		String extName = map.get("extName").toString();
		// 取得图片的id
		int imgId = Globals.allIconImgs.get(extName);
		// 设置图片
		fileImg.setBackgroundResource(imgId);

		return convertView;
	}

}

四、编写Activity

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.liky.file.adapter.FileAdapter;
import org.liky.file.util.Globals;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView titleText;
	private ListView list;

	private FileAdapter adapter;
	private List<Map<String, Object>> allValues = new ArrayList<Map<String, Object>>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Globals.init(this);

		setContentView(R.layout.activity_main);

		// 取得组件
		titleText = (TextView) findViewById(R.id.title_text);
		list = (ListView) findViewById(R.id.list);

		// 准备数据
		// 取得SD卡根目录
		File root = Environment.getExternalStorageDirectory();

		loadFileData(root);

		// 建立Adapter
		adapter = new FileAdapter(this, allValues);

		list.setAdapter(adapter);

		// 加入监听事件
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// 取得当前操作的数据
				Map<String, Object> map = allValues.get(arg2);
				// 判断所点的是文件还是文件夹
				boolean dirFlag = (Boolean) map.get("dirFlag");
				if (dirFlag) {
					// 文件夹
					// 建立该文件夹的File对象
					// 取得绝对路径
					String fullPath = (String) map.get("fullPath");
					// 建立File
					File dir = new File(fullPath);

					// 先清空原有数据
					allValues.clear();

					if (!Environment.getExternalStorageDirectory()
							.getAbsolutePath().equals(fullPath)) {
						// 加入返回上一级的操作行
						Map<String, Object> parent = new HashMap<String, Object>();
						parent.put("fileName", "返回上一级");
						parent.put("extName", "dir_open");
						parent.put("dirFlag", true);
						parent.put("fullPath", dir.getParent());

						// 保存一个标志
						parent.put("flag", "TRUE");

						// 将这一行加入到数据集合中
						allValues.add(parent);
					}

					// 加入新数据
					loadFileData(dir);

					// 使用Adapter通知界面ListView,数据已经被修改了,你也要一起改
					adapter.notifyDataSetChanged();
				} else {
					// 弹出该文件的详细信息
					File f = new File((String) map.get("fullPath"));

					// 建立对话框
					Builder builder = new Builder(MainActivity.this);

					builder.setTitle("详细信息");
					builder.setMessage("文件大小: " + f.length() + "\r\n" + "文件名:"
							+ f.getName());

					// 最多允许加入3个按钮,
					// 注意监听中导入的支持包不再是之前的OnCliCkListener,而是DialogInterface下的这个监听
					builder.setPositiveButton("关闭", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});

					// 建立对话框,并显示
					builder.create().show();

				}

			}
		});

		list.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {
				// 取得数据
				Map<String, Object> map = allValues.get(arg2);
				final File f = new File(map.get("fullPath").toString());

				if (f.isFile()) {
					// 弹出确认框
					Builder builder = new Builder(MainActivity.this);
					builder.setTitle("提示");
					builder.setMessage("确定要删除该文件(" + f.getName() + ")吗?");
					builder.setPositiveButton("确定", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 将SD卡中的文件删除
							if (f.exists()) {
								f.delete();
							}

							// 将列表中的数据删除
							allValues.remove(arg2);
							// 通知
							adapter.notifyDataSetChanged();
						}
					});
					builder.setNegativeButton("取消", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});

					builder.create().show();
				}

				return false;
			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 根据keyCode判断用户按下了哪个键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 判断当前是否在SD卡跟目录.
			// 取得第一行数据
			Map<String, Object> map = allValues.get(0);
			if ("TRUE".equals(map.get("flag"))) {
				// 里面,需要返回上一级
				list.performItemClick(list.getChildAt(0), 0, list.getChildAt(0)
						.getId());
			} else {
				// 弹出提示框
				Builder builder = new Builder(MainActivity.this);
				builder.setTitle("提示");
				builder.setMessage("亲,真的要离开我吗?");
				builder.setPositiveButton("真的", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 关闭当前Activity
						finish();
					}
				});
				builder.setNegativeButton("再待会儿", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});
				builder.create().show();
			}

			return false;
		}

		return super.onKeyDown(keyCode, event);
	}

	private void loadFileData(File dir) {
		// 列出该目录下的所有文件
		File[] allFiles = dir.listFiles();
		// 设置当前位置的提示信息
		titleText.setText("当前位置: " + dir.getAbsolutePath());

		// 判断
		if (allFiles != null) {
			// 循环
			for (int i = 0; i < allFiles.length; i++) {
				File f = allFiles[i];
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("fileName", f.getName());
				// 多保存一个文件的绝对路径,方便在进行点击时使用
				map.put("fullPath", f.getAbsolutePath());
				// 判断是文件夹还是文件
				if (f.isDirectory()) {
					// 是文件夹
					map.put("extName", "dir_close");
					map.put("dirFlag", true);
				} else {
					// 是文件
					// 截取出扩展名
					String extName = f.getName()
							.substring(f.getName().lastIndexOf(".") + 1)
							.toLowerCase();
					map.put("extName", extName);
					map.put("dirFlag", false);
				}

				allValues.add(map);
			}
		}
	}

}




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: