android 手把手教你打造属于自己的文件浏览器

前言

相信很多朋友在项目开发中都需要用到选择文件浏览器,但是打开的的文件浏览器总有很多不是很满足的地方,比如说只显示特定的文件 还有就是只选择文件夹的路径,这种需求相信在实际开发中还是会遇到很多的,在这里就需要我们自己根据File这个类和android的ListView来完成一个简单的文件浏览器 ,所以让我们来打造属于自己的文件浏览器吧

思路:

其实很简单的 我们只需要根据获取到的手机的sd卡根目录来获取到 每个目录的子目录,在每次点击的时候刷新ListView就可以了,现在让我们看下 项目演示

这里写图片描述

现在让我们来实现主界面的逻辑


对于主界面,我们只需要重写他的onActivityResult方法,并且在点击按钮的时候对选择存储区域的一个选择逻辑就可以了,现在是代码

package com.browser.blue.filebrowser;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName() + "--->";
    public static final int FILE_RESULT_CODE = 1;
    private Button btn_open;
    private TextView changePath;

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

    private void initView() {
        btn_open = (Button) findViewById(R.id.btn_open);
        changePath = (TextView) findViewById(R.id.changePath);
    }

    private void initListener() {
        btn_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openBrowser();
            }
        });
    }

    private void openBrowser() {
        new AlertDialog.Builder(this).setTitle("选择存储区域").setIcon(
                R.drawable.icon_opnefile_browser).setSingleChoiceItems(
                new String[]{"内置sd卡", "外部sd卡"}, 0,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(MainActivity.this, FileBrowserActivity.class);
                        if (which == 0)
                            intent.putExtra("area", false);
                        else
                            intent.putExtra("area", true);
                        startActivityForResult(intent, FILE_RESULT_CODE);
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", null).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (FILE_RESULT_CODE == requestCode) {
            Bundle bundle = null;
            if (data != null && (bundle = data.getExtras()) != null) {
                String path = bundle.getString("file");
                Log.d(TAG, "onActivityResult: " + path);
                changePath.setText("选择路径为 : " + path);
            }
        }
    }
}

可以看到我们在onActivityResult中获取到选择后的文件路径直接将它显示到TextView上面,下面就是文件浏览器的核心部分了

FileBrowserActivity.java 我们将它直接继承一个ListAcitivity,下面是整个代码

package com.browser.blue.filebrowser;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;

import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

/**
 * Created by blue on 2016/10/23.
 */

public class FileBrowserActivity extends ListActivity {
    private static final String TAG = FileBrowserActivity.class.getSimpleName() + "--->";
    private String rootPath;
    private boolean pathFlag;
    private List<String> pathList;
    private List<String> itemsList;
    private TextView curPathTextView;

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

    private void initInfo() {
        pathFlag = getIntent().getBooleanExtra("area", false);
        rootPath = getRootPath();
        if (rootPath == null) {
            Toast.makeText(this, "所选SD卡为空!", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            getFileDir(rootPath);
        }
    }

    private void initView() {
        curPathTextView = (TextView) findViewById(R.id.curPath);
    }


    private void getFileDir(String filePath) {
        curPathTextView.setText(filePath);
        itemsList = new ArrayList<>();
        pathList = new ArrayList<>();
        File file = new File(filePath);
        File[] files = file.listFiles();
        if (!filePath.equals(rootPath)) {
            itemsList.add("b1");
            pathList.add(rootPath);
            itemsList.add("b2");
            pathList.add(file.getParent());
        }
        if (files == null) {
            Toast.makeText(this, "所选SD卡为空!", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        for (int i = 0; i < files.length; i++) {
            File f = files[i];
           /**这里取消注释 就能显示到指定的文件了*/
           // if (checkSpecificFile(f)) {
                itemsList.add(f.getName());
                pathList.add(f.getPath());
         //   }
        }
        setListAdapter(new MyAdapter(this, itemsList, pathList));
    }

    public boolean checkSpecificFile(File file) {
        String fileNameString = file.getName();
        String endNameString = fileNameString.substring(
                fileNameString.lastIndexOf(".") + 1, fileNameString.length())
                .toLowerCase();
        Log.d(TAG, "checkShapeFile: " + endNameString);
        if (file.isDirectory()) {
            return true;
        }
        /**甚至需要显示的特定文件后缀*/
        if (endNameString.equals("txt")) {
            return true;
        } else {
            return false;
        }
    }

    private String getRootPath() {

        try {
            String rootPath;
                if (pathFlag) {
                    Log.d(TAG, "getRootPath: 正在获取内置SD卡根目录");
                    rootPath = Environment.getExternalStorageDirectory()
                            .toString();
                    Log.d(TAG, "getRootPath: 内置SD卡目录为:" + rootPath);
                    return rootPath;
                } else {
                    rootPath = System.getenv("SECONDARY_STORAGE");
                    if ((rootPath.equals(Environment.getExternalStorageDirectory().toString())))
                        rootPath = null;
                    Log.d(TAG, "getRootPath:  外置SD卡路径为:" + rootPath);
                    return rootPath;
            }
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        File file = new File(pathList.get(position));
        if (file.isDirectory()) {
            getFileDir(file.getPath());
        } else {
            Intent data = new Intent(FileBrowserActivity.this, MainActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("file", file.getPath());
            data.putExtras(bundle);
            setResult(2, data);
            finish();
        }
    }

    public boolean checkSDcard() {
        String sdStutusString = Environment.getExternalStorageState();
        if (sdStutusString.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
}

然后就是ListView的adapter了,对于adapter其实与平时的adapter都差不多

package com.browser.blue.filebrowser;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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 java.io.File;
import java.util.List;

public class MyAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    private Bitmap mIcon1;
    private Bitmap mIcon2;
    private Bitmap mIcon3;
    private Bitmap mIcon4;
    private List<String> items;
    private List<String> paths;

    public MyAdapter(Context context, List<String> it, List<String> pa) {
        mInflater = LayoutInflater.from(context);
        items = it;
        paths = pa;
        mIcon1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_back);
        mIcon2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_back02);
        mIcon3 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_fodler);
        mIcon4 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_file);
    }
    public int getCount() {
        return items.size();
    }
    public Object getItem(int position) {
        return items.get(position);
    }
    public long getItemId(int position) {
        return position;
    }
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.file_item, null);
            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.text);
            holder.icon = (ImageView) convertView.findViewById(R.id.icon);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        File f = new File(paths.get(position).toString());
        if (items.get(position).toString().equals("b1")) {
            holder.text.setText("返回根目录..");
            holder.icon.setImageBitmap(mIcon1);
        } else if (items.get(position).toString().equals("b2")) {
            holder.text.setText("返回上一层..");
            holder.icon.setImageBitmap(mIcon2);
        } else {
            holder.text.setText(f.getName());
            if (f.isDirectory()) {
                holder.icon.setImageBitmap(mIcon3);
            } else {
                holder.icon.setImageBitmap(mIcon4);
            }
        }
        return convertView;
    }
    private class ViewHolder {
        TextView text;
        ImageView icon;
    }
}

布局文件就不一一展示了,只展示下 FileBrowserAcitivty的布局吧

<?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:orientation="vertical">
    <TextView
        android:id="@+id/curPath"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:textSize="18sp">
    </TextView>
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="match_parent">
    </ListView>
</LinearLayout>

对于这个文件浏览器其实也是很简单的,需要源码的同学请到我的github下载

自定义文件浏览器 点击进入

  • 6
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值