Android初学之第一个Android程序:文件浏览器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013483704/article/details/52047981

文件浏览器笔记

文件浏览器用来读取android系统中的所有文件和文件夹。具体说明如下:

  1. 最上面显示当前的文件路径。如果是根目录,则显示“/”;
  2. 第二行是返回上一级按钮。如果当前处于根目录下,则该行不显示;
  3. 若当前是文件夹,则可点击,进入下一级目录,若是文件,点击的话会提示不支持读取。

新加功能,监听外部存储设备USB和SD卡插拔广播。代码如下:

public class UsbBroadCastReceiver extends BroadcastReceiver {

    @SuppressLint("ShowToast")
    @Override
    public void onReceive(final Context context, final Intent intent) {
        final String action = intent.getAction();
        final IntentFilter iFilter = new IntentFilter();
        iFilter.addDataScheme("file");

        if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
            Toast.makeText(context, "外部存储设备已移除", 1000).show();
        } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
            Toast.makeText(context, "正在准备外部USB存储设备", 1000).show();
        } else if (action.equals(Intent.ACTION_MEDIA_CHECKING)) {
            Toast.makeText(context, "正在准备外部SD卡存储设备", 1000).show();
        }

    }

当然还要在AndroidMainfest.xml中添加相应配置:

    <receiver android:name="browers.UsbBroadCastReceiver" >
            <intent-filter android:priority="1000" >
                <action android:name="android.intent.action.MEDIA_MOUNTED" />
                <action android:name="android.intent.action.MEDIA_EJECT" />
                <action android:name="android.intent.action.MEDIA_CHECKING" />

                <data android:scheme="file" />
            </intent-filter>
     </receiver>

下面是主要的程序源码:

FileManager.java

package browers;

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

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.example.browers.R;

public class FileManager extends Activity {
    private TextView mCurrentPath;
    private TextView mReturn;
    private ListView mList;
    private View mPathLine;
    private String mReturnPath = null;
    private FileManagerAdapter adapter;
    private ArrayList<Map<String, Object>> infos = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.file_list);
        initView();
    }

    private void initView() {
        mCurrentPath = (TextView) findViewById(R.id.file_path);
        mPathLine = findViewById(R.id.file_path_line);
        mReturn = (TextView) findViewById(R.id.file_return);
        mList = (ListView) findViewById(R.id.file_list);

      //为listview添加一个响应事件
        mList.setOnItemClickListener(clickListener);
      //处理用户短时间单击按钮的事件
        mReturn.setOnClickListener(new OnClickListener() {

          //如果出现返回上一级字符和mreturnpath长度不等于0,则初始化返回的那个路径
            @Override
            public void onClick(View v) {
                String returnStr = mReturn.getText().toString();
                if (mReturnPath.length() > 0 && returnStr.equals("返回上一级")) {
                    initList(mReturnPath);
                }

            }
        });

        initList("/"); // 初始化从根目录开始
    }

    private void initList(String path) {
        File file = new File(path);
        File[] fileList = file.listFiles();
        infos = new ArrayList<Map<String, Object>>();
        Map<String, Object> item = new HashMap<String, Object>();
        Drawable drawable;
        if (path.equals("/")) { // 如果当前为根目录,返回上一级按钮,不显示
            drawable = getResources().getDrawable(R.drawable.root_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                    drawable.getMinimumHeight());
            mCurrentPath.setCompoundDrawablePadding(10);
            mCurrentPath.setCompoundDrawables(drawable, null, null, null);
            mCurrentPath.setText("根目录列表");
            mReturn.setVisibility(View.GONE);
            mPathLine.setVisibility(View.GONE);
        } else {
            drawable = getResources().getDrawable(R.drawable.root_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                    drawable.getMinimumHeight());
            mReturn.setCompoundDrawables(drawable, null, null, null);
            mReturn.setText("返回上一级");
            mReturnPath = file.getParent(); // 保存该级目录的上一级路径
            mCurrentPath.setVisibility(View.VISIBLE);
            mPathLine.setVisibility(View.VISIBLE);
            mCurrentPath.setText(file.getPath());
        }

        try {
            for (int i = 0; i < fileList.length; i++) {
                item = new HashMap<String, Object>();
                File fileItem = fileList[i];
                if (fileItem.isDirectory()) { // 如果当前文件为文件夹,设置文件夹的图标
                    item.put("icon", R.drawable.floder_icon);
                } else
                    item.put("icon", R.drawable.child_icon);
                item.put("name", fileItem.getName()); //实例化item对象
                item.put("path", fileItem.getAbsolutePath());
                infos.add(item);//将item对象添加到infos集合中
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        adapter = new FileManagerAdapter(this);
        adapter.setFileListInfo(infos);
        mList.setAdapter(adapter);
    }

    private final OnItemClickListener clickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                long arg3) {
            File file = new File((String) (infos.get(position).get("path")));
            if (file.isDirectory()) { // 若点击文件夹,则进入下一级目录
                String nextPath = (String) (infos.get(position).get("path"));
                initList(nextPath);
            } else { // 若点击文件,则将文件名发送至调用文件浏览器的主界面
                Intent intent = new Intent();
                intent.setClass(FileManager.this, Activity.class);
                intent.putExtra("fileName",
                        (String) (infos.get(position).get("name")));
                intent.putExtra("path",
                        (String) (infos.get(position).get("path")));
                setResult(RESULT_OK, intent);
                finish();
            }

        }
    };
}

相应的adapter文件:

FileManagerAdapter.java

package browers;

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

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;

import com.example.browers.R;

public class FileManagerAdapter extends BaseAdapter {
    private final Context mContext;
    private final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

    public FileManagerAdapter(final Context context) {
        super();
        mContext = context;
    }

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

    @Override
    public Object getItem(final int position) {
        return position;
    }

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

    @Override
    public View getView(final int position, View convertView,
            final ViewGroup arg2) {
        FileMangerHolder holder;

        if (null == convertView) {
            holder = new FileMangerHolder();
            convertView = LayoutInflater.from(mContext).inflate(
                    R.layout.file_item, null);
            holder.icon = (ImageView) convertView
                    .findViewById(R.id.file_item_icon);
            holder.name = (TextView) convertView
                    .findViewById(R.id.file_item_name);
            convertView.setTag(holder);
        } else {
            holder = (FileMangerHolder) convertView.getTag();
        }

        holder.icon
                .setImageResource((Integer) (list.get(position).get("icon")));
        holder.name.setText((String) (list.get(position).get("name")));

        return convertView;
    }

    public class FileMangerHolder {
        public ImageView icon;
        public TextView name;
    }

    // The information add to listView
    public void setFileListInfo(final List<Map<String, Object>> infos) {
        list.addAll(infos);
        notifyDataSetChanged();
    }
}

最后是两个布局文件:file_list.xml和file_item.xml

file_list.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"
    android:background="@color/black"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/file_path"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="left|center"
        android:layout_margin="5dp"
        android:ellipsize="end"
        android:singleLine="true"
        android:textColor="@color/white"
        android:textSize="21sp" />

    <View
        android:id="@+id/file_path_line"
        android:layout_width="match_parent"
        android:layout_height="0.3dp"
        android:background="@color/dimgray" />

    <TextView
        android:id="@+id/file_return"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="left|center"
        android:layout_margin="5dp"
        android:textColor="@color/yellow"
        android:textSize="17sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0.3dp"
        android:background="@color/dimgray" />

    <ListView
        android:id="@+id/file_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:cacheColorHint="#00000000"
        android:divider="@color/dimgray"
        android:dividerHeight="0.3dp"
        android:listSelector="@null"
        android:scrollbars="vertical" />

</LinearLayout>

file_item.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"
    android:gravity="center_vertical"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="46dp" >

        <ImageView
            android:id="@+id/file_item_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" />

        <TextView
            android:id="@+id/file_item_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_margin="55dp"
            android:ellipsize="end"
            android:singleLine="true"
            android:textColor="@color/white"
            android:textSize="17sp" />
    </RelativeLayout>

</LinearLayout>

以上是全部源码,换了环境运得时,包名可能需要根据自己的目录路径做一下相应的更改,其他的基本没有问题,程序很简单,也可以很好的进行拓展。

猜你喜欢

转载自blog.csdn.net/u013483704/article/details/52047981