android选择文件(安卓系统文件夹详解)
android选择文件(安卓系统文件夹详解)
2024-11-25 01:13:20  作者:個悳冬天  网址:https://m.xinb2b.cn/know/thh296065.html

废话没有,先看效果


第一步:创建MainActivity

import android.app.Activity;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import com.rdsa.singleselectedfileorfolder.R;import java.util.ArrayList;public class MainActivity extends AppCompatActivity {    public Context mContext;    private Button selectFile, selectFolder, mSelectFile, mSelectFolder;    private TextView result;    private Activity activity;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        this.mContext = this;        this.activity = this;        setContentView(R.layout.activity_main);        initView();        initData();        initEvent();    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        if (requestCode == ChooseFileOrDirActivity.RequestCode && resultCode == ChooseFileOrDirActivity.ResultCode) {            ArrayList<String> resPath = data.getStringArrayListExtra(ChooseFileOrDirActivity.ResultData);            StringBuffer sb = new StringBuffer();            for(String item : resPath) {                sb.append(item).append("rn");            }            result.setText(sb.toString());        }    }    private void initView() {        this.result = super.findViewById(R.id.result);        this.selectFile = super.findViewById(R.id.selectFile);        this.selectFolder = super.findViewById(R.id.selectFolder);        this.mSelectFile = super.findViewById(R.id.mSelectFile);        this.mSelectFolder = super.findViewById(R.id.mSelectFolder);    }    private void initData() {    }    private void initEvent() {        selectFile.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Intent intent = new Intent(activity, ChooseFileOrDirActivity.class);                intent.putExtra(ChooseFileOrDirActivity.EnterVar, ChooseFileOrDirActivity.SingleFile);                activity.startActivityForResult(intent, ChooseFileOrDirActivity.RequestCode);            }        });        selectFolder.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Intent intent = new Intent(activity, ChooseFileOrDirActivity.class);                intent.putExtra(ChooseFileOrDirActivity.EnterVar, ChooseFileOrDirActivity.SingleFolder);                activity.startActivityForResult(intent, ChooseFileOrDirActivity.RequestCode);            }        });        mSelectFile.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Intent intent = new Intent(activity, ChooseFileOrDirActivity.class);                intent.putExtra(ChooseFileOrDirActivity.EnterVar, ChooseFileOrDirActivity.MultiFile);                activity.startActivityForResult(intent, ChooseFileOrDirActivity.RequestCode);            }        });        mSelectFolder.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Intent intent = new Intent(activity, ChooseFileOrDirActivity.class);                intent.putExtra(ChooseFileOrDirActivity.EnterVar, ChooseFileOrDirActivity.MultiFolder);                activity.startActivityForResult(intent, ChooseFileOrDirActivity.RequestCode);            }        });    }}

第二步:创建MainActivity布局文件activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.rdsa.selectedfileorfolder.MainActivity">    <Button        android:id="@+id/selectFolder"        android:text="文件夹选择(单选)"        android:layout_width="match_parent"        android:layout_height="wrap_content"   />    <Button        android:id="@+id/selectFile"        android:text="文件选择(单选)"        android:layout_width="match_parent"        android:layout_height="wrap_content"   />    <Button        android:id="@+id/mSelectFolder"        android:text="文件夹选择(多选)"        android:layout_width="match_parent"        android:layout_height="wrap_content"   />    <Button        android:id="@+id/mSelectFile"        android:text="文件选择(多选)"        android:layout_width="match_parent"        android:layout_height="wrap_content"   />    <TextView        android:id="@+id/result"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Wait for Result" /></LinearLayout>

第三步:创建目录数据存储类FileOrDirBeans

public class FileOrDirBeans {    String isFile, name, isCheckVisible, isChecked, absolutePath ;    public FileOrDirBeans(String... params) {        this.isFile = params[0];        this.name = params[1];        this.isCheckVisible = params[2];        this.isChecked = params[3];        this.absolutePath = params[4];    }    public String getIsFile() {        return isFile;    }    public void setIsFile(String isFile) {        this.isFile = isFile;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getIsCheckVisible() {        return isCheckVisible;    }    public void setIsCheckVisible(String isCheckVisible) {        this.isCheckVisible = isCheckVisible;    }    public String getIsChecked() {        return isChecked;    }    public void setIsChecked(String isChecked) {        this.isChecked = isChecked;    }    public String getAbsolutePath() {        return absolutePath;    }    public void setAbsolutePath(String absolutePath) {        this.absolutePath = absolutePath;    }}

第四步:创建文件浏览ChooseFileOrDirActivity

import android.Manifest;import android.app.Activity;import android.content.Intent;import android.content.pm.PackageManager;import android.os.Build;import android.os.Bundle;import android.os.Environment;import android.view.KeyEvent;import android.view.View;import android.widget.Button;import android.widget.ListView;import android.widget.TextView;import com.rdsa.singleselectedfileorfolder.R;import java.io.File;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.List;public class ChooseFileOrDirActivity extends Activity {    public static final String EnterVar = "EnterVar";    public static final String ResultData = "SELECTED";    public static final int RequestCode = 888;    public static final int ResultCode = 999;    public static final int SingleFile = 1000;    public static final int SingleFolder = 2000;    public static final int MultiFile = 3000;    public static final int MultiFolder = 2001;    private String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath();    private static final int REQUESCODE = 5;    private static final String NEED_PERMISSION = Manifest.permission.WRITE_EXTERNAL_STORAGE;    private ListView listView4File;    private TextView noDataTip;    private Button btChose;    private List<String> data;    private ArrayList<FileOrDirBeans> fileOrDirList;    private FileAdapter fileAdapter;    private int enterVar;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.ly_choose_file_or_folder);        this.enterVar = this.getIntent().getIntExtra(EnterVar, SingleFile);        this.initView();        this.initData();        this.initEvent();    }    private void initData() {        this.listView4File.setEmptyView(noDataTip);        this.data = new ArrayList<>();        this.fileOrDirList = new ArrayList<>();        this.fileAdapter = new FileAdapter(this, fileOrDirList, enterVar);        this.listView4File.setAdapter(fileAdapter);        if (Build.VERSION.SDK_INT >= 23) {      // 判断系统版本是否大于6.0            if (checkSelfPermission(NEED_PERMISSION) == PackageManager.PERMISSION_GRANTED) {  //检查是否有读写权限                loadDataFromPath(rootPath, enterVar);//从路径中加载数据            } else {                requestPermissions(new String[]{NEED_PERMISSION}, REQUESCODE); // 申请权限            }        } else {            loadDataFromPath(rootPath, enterVar);//系统版本小于6.0直接加载数据        }    }    private void loadDataFromPath(final String mPath, final int type) {        this.data.clear();    // data为 ListView 中要显示的数据        this.fileOrDirList.clear();        new Thread() {            public void run() {                super.run();                data = orderByName(mPath, type == SingleFolder || type == MultiFolder);                fileOrDirList = getBeans(data, type);                runOnUiThread(new Runnable() {@Overridepublic void run() {    fileAdapter.setData(data, fileOrDirList);//将数据载入适配器当中}                });            }        }.start();    }    private ArrayList<FileOrDirBeans> getBeans(List<String> fileList, final int type) {        ArrayList<FileOrDirBeans> resultList = new ArrayList<>();        for(String fileItem : fileList) {            File file = new File(fileItem);            String isFile = String.valueOf(file.isFile());            String isCheckVisible = (file.isFile() || type == SingleFolder || type == MultiFolder) ?  "true" : "false";;            FileOrDirBeans bean = new FileOrDirBeans(isFile, file.getName(), isCheckVisible, "false", fileItem);            resultList.add(bean);        }        return resultList;    }    private void initView() {        listView4File = findViewById(R.id.rvFileView);        noDataTip = findViewById(R.id.noDataTip);    }    private void initEvent() {        fileAdapter.setEvent(new FileAdapter.Event() {            @Override            public void enterNextDir(String path) {                rootPath = path;                loadDataFromPath(rootPath, enterVar);            }        });        findViewById(R.id.btChose).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Intent intent = new Intent();                intent.putStringArrayListExtra(ResultData, fileAdapter.getSelectData());                setResult(ResultCode, intent);                finish();            }        });    }    @Override    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {        super.onRequestPermissionsResult(requestCode, permissions, grantResults);        if (requestCode == REQUESCODE && permissions[0].equals(NEED_PERMISSION)) {            loadDataFromPath(rootPath, enterVar);        }    }    @Override    public boolean onKeyDown(int keyCode, KeyEvent event) {        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {//点击的是返回键            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {//按键的按下事件                if (rootPath.trim().equals(Environment.getExternalStorageDirectory().getAbsolutePath())) {return super.onKeyDown(keyCode, event);                } else {File file = new File(rootPath);if (!file.exists()) {    return super.onKeyDown(keyCode, event);}rootPath = file.getParent();loadDataFromPath(rootPath, enterVar);return false;                }            }        }        return super.onKeyDown(keyCode, event);    }    public static ArrayList<String> orderByName(String filePath, boolean excludeFile) {        ArrayList<String> FileNameList = new ArrayList<String>();        File file = new File(filePath);        File[] files = file.listFiles();        List fileList = Arrays.asList(files);        Collections.sort(fileList, new Comparator<File>() {            @Override            public int compare(File o1, File o2) {                if (o1.isDirectory() && o2.isFile())return -1;                if (o1.isFile() && o2.isDirectory())return 1;                return o1.getName().compareTo(o2.getName());            }        });        for (File itemFile : files) {            if(itemFile.getName().startsWith(".")) {                continue;            } else {                if(itemFile.isFile() && excludeFile) {continue;                }                FileNameList.add(itemFile.getAbsolutePath());  //往集合中添加符合条件的数据            }        }        return FileNameList;    }}

第五步:创建ChooseFileOrDirActivity布局文件ly_choose_file_or_folder.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:orientation="vertical" >    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="50dp"        android:background="#F9F9FA">        <TextView            android:id="@+id/tvTitle"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true" />        <Button            android:id="@+id/btChose"            android:layout_width="wrap_content"            android:layout_height="30dp"            android:layout_alignParentRight="true"            android:layout_centerVertical="true"            android:layout_marginRight="5dp"            android:background="@drawable/bg_button"            android:text="确定"            android:textColor="#458B74" />    </RelativeLayout>    <ListView        android:id="@+id/rvFileView"        android:layout_width="match_parent"        android:layout_height="match_parent" />    <TextView        android:id="@+id/noDataTip"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center_vertical|center_horizontal"        android:text="没有数据可用,返回上一层" /></LinearLayout>

第六步:创建ListView的数据容器类FileAdapter

import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.CheckBox;import android.widget.CompoundButton;import android.widget.ImageView;import android.widget.TextView;import com.rdsa.singleselectedfileorfolder.R;import java.util.ArrayList;import java.util.List;public class FileAdapter extends BaseAdapter {    private Context context;    private Event event;    private ArrayList<String> selectData;    private ArrayList<FileOrDirBeans> fileOrDirList;    private LayoutInflater mLayoutInflater;      //   将 Item 的 XML 转换成 View    private final int enterVar;    public FileAdapter(Context context, final ArrayList<FileOrDirBeans> fileOrDirList, int enterVar) {        this.context = context;        this.selectData = new ArrayList<>();        this.mLayoutInflater = LayoutInflater.from(context);     // context 必须是界面所在的 context        this.enterVar = enterVar;        this.fileOrDirList = fileOrDirList;    }    @Override    public int getCount() {        return this.fileOrDirList.size();    }    @Override     // 数据项    public Object getItem(int position) {        return fileOrDirList.get(position);    }    @Override    public long getItemId(int position) {        return position;    }    @Override    // 显示的内容    public View getView(final int position, View convertView, ViewGroup viewGroup) {        ViewHolder viewHolder;        if(convertView == null) {            convertView = mLayoutInflater.inflate(R.layout.filechoose_layout_fileitme, null);            viewHolder = new ViewHolder();            viewHolder.icon = convertView.findViewById(R.id.icon);            viewHolder.fileName = convertView.findViewById(R.id.fileName);            viewHolder.checkBox = convertView.findViewById(R.id.checkBox);            convertView.setTag(viewHolder);        } else {            viewHolder = (ViewHolder)convertView.getTag();        }        final FileOrDirBeans bean = fileOrDirList.get(position);        final String absPath = bean.getAbsolutePath();        bean.setIsChecked("false");    //   初始化一个boolean值 来判断是否被选中        for (String s : selectData) {    // 遍历选中的集合            if (s.trim().equals(absPath)) {    // 如果集合中的子元素与适配其中的路径相同                bean.setIsChecked("true");     // 判断已被选中                break; //终止循环            }        }        viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {            @Override            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {//设置checkBox的点击事件                if (isChecked) {//选中状态if (selectData.contains(absPath)) {//如果集合中包含了该元素则直接返回    if (enterVar == ChooseFileOrDirActivity.SingleFile || enterVar == ChooseFileOrDirActivity.SingleFolder) {        selectData.clear();        selectData.add(absPath);    }} else {//否则添加    if(enterVar == ChooseFileOrDirActivity.SingleFile || enterVar == ChooseFileOrDirActivity.SingleFolder) {        selectData.clear();    }    selectData.add(absPath);}                } else {//未选中状态if (selectData.contains(absPath)) {//如果集合中包含了该元素则移除    selectData.remove(absPath);} else {//否则 返回    return;}                }                notifyDataSetChanged();            }        });        viewHolder.icon.setImageDrawable(Boolean.parseBoolean(bean.getIsFile()) ?  context.getResources().getDrawable(R.drawable._16_file) : context.getResources().getDrawable(R.drawable._16_folder));        viewHolder.fileName.setText(bean.getName());        viewHolder.checkBox.setVisibility((Boolean.parseBoolean(bean.isCheckVisible))?  View.VISIBLE : View.GONE);        viewHolder.checkBox.setChecked(Boolean.parseBoolean(bean.getIsChecked()));        viewHolder.fileName.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                if(!Boolean.parseBoolean(bean.getIsFile())) {event.enterNextDir(fileOrDirList.get(position).getAbsolutePath());                }            }        });        return convertView;    }    static class ViewHolder {        private ImageView icon;        private TextView fileName;        private CheckBox checkBox;    }    public interface Event {        void enterNextDir(String path);//进入下一个文件夹    }    public void setData(List<String> data, ArrayList<FileOrDirBeans> fileOrDirList) {        this.fileOrDirList.clear();        this.fileOrDirList.addAll(fileOrDirList);        notifyDataSetChanged();    }    public void setEvent(Event event) {        this.event = event;    }    public ArrayList<String> getSelectData() {        return selectData;    }}

第七步:创建FileAdapter每一项的布局文件filechoose_layout_fileitme.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal" >    <ImageView        android:id="@+id/icon"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginStart="8dp"        android:layout_marginEnd="8dp"        android:layout_alignParentStart="true"        android:layout_centerVertical="true"        android:src="@drawable/file" />    <TextView        android:id="@+id/fileName"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginBottom="8dp"        android:layout_marginTop="8dp"        android:paddingRight="50dp"        android:layout_toRightOf="@+id/icon"        android:layout_centerVertical="true"        android:text="TextView"  />    <CheckBox        android:id="@+id/checkBox"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentEnd="true"        android:layout_centerVertical="true"        android:layout_marginEnd="8dp" /></RelativeLayout>

第八步:AndroidManifest 增加对文件操作的授权

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

第九步:用到的图片资源_16_file.jpg"和_16_folder.jpg"

  • 钢笔刻字经典句子(钢笔刻字经典句子有哪些)
  • 2024-11-25钢笔刻字经典句子有哪些后来,海底月捞不起,眼前人不可提大明国第一定律千万别惹王守仁我向圣诞老人许了愿,不管你的脚有多臭,在明天你穿起袜子时,你会收到我托圣诞老人带给你的满满祝福,来温暖你的心和脚丫幸福,不是长生不老,不是大。
  • 兴化市钓鱼镇网站 兴化钓鱼工作站
  • 2024-11-25兴化市钓鱼镇网站 兴化钓鱼工作站来源:【交汇点新闻客户端】9月18日,由江苏省农业科学院粮食作物研究所、江苏沿海地区农业科学研究所、兴化市农业农村局和兴化市钓鱼镇政府共建的江苏省农科院亚夫科技服务“兴化钓鱼工作站”揭牌仪式在兴化市举。
  • 北京京师律师事务所成员(京师深圳联合创始人陈修)
  • 2024-11-25京师深圳联合创始人陈修陈修主任北京市京师(深圳)律师事务所联合创始人深圳市律所职业经理人研究院首任院长开篇立意先抛个问题:你觉得律所的管理水平在全社会处于什么段位?初涉律师行业的陈修主任也曾以为,既然是面向高度自律、高规范。
  • 鸡肉如何焯水才正确(鸡肉怎样焯水才正确)
  • 2024-11-25鸡肉怎样焯水才正确将购鸡肉,洗净切块,锅中烧开水,放入洗干净的鸡块锅沸腾后,撇去浮起来沫用漏勺捞出控水即可鸡肉指鸡身上的肉,鸡的肉质细嫩,滋味鲜美,适合多种烹调方法,并富有营养,有滋补身体的作用鸡肉很容易被人体吸收利用。
  • 吕良伟的老婆杨小娟是什么人(贵州女婿吕良伟)
  • 2024-11-25贵州女婿吕良伟宛如在功夫片《导火线》中,“渣哥”吕良伟跳舞的视频成为经典,虽然他并非专业舞者,却没人能够超越他那嚣张跋扈的样子有网友曾如此调侃:待我把欠下的债还完,也要像“渣哥”那样跳舞《达摩祖师》剧照就演技而言,。
  • 不明白的相近词
  • 2024-11-25不明白的相近词相近词:不清楚造句1)他说得挺含糊,我不明白是什么意思2)小兰说话非常含蓄,常让我们弄不明白她的意思3)他反复讲解了这个问题,但同学们还是不明白4)小明的作文如同天马行空,大家都看不明白5)我在这方面。
  • 青铜之冠是指什么(青铜之冠介绍)
  • 2024-11-25青铜之冠介绍青铜之冠指的是:秦陵铜车马1980年于秦始皇陵封土西侧20米处发掘出土的一组两乘大型的彩绘铜车马—高车和安车,是迄今中国发现的体形最大、装饰最华丽,结构和系驾最逼真、最完整的古代铜车马,被誉为“青铜之。
  • 这些家用suv最值得期待年后就开卖(20万元级合资SUV海选)
  • 2024-11-2520万元级合资SUV海选在20万元级的合资SUV市场中,德系和日系无疑是火药味最浓的一对对于很多人来说,这两边都是个不错的选择,但是如何买到一辆称心如意的车就变得事关重要了在这个价位里,就属大众探岳、丰田RAV4荣放、本田C。
  • 星之守护者特效端游(星风收购皇冠守护者游戏版权)
  • 2024-11-25星风收购皇冠守护者游戏版权缺乏创意的游戏时代,越来越多的厂商开始想目标瞄向那些经典游戏品牌,意图将上世纪的一些经典游戏重新带回我们的视线中近日瑞典星风(Starbreeze)工作室就从北美公司Cinemaware手中收购了一些。
  • 提线木偶的寓意
  • 2024-11-25提线木偶的寓意答案:提线木偶的寓意没有主见,听从他人安排的寓意提线木偶比喻是没有主见,听从他人安排的人所表达意思是一种木偶戏讽刺,没有主见通常在句中做定语,位于修饰主语或宾语例如你想把我们当提线木偶,就得付钱给方舟。
  • 陈小艺和丈夫没有共同语言 陈小艺的奇葩婚姻
  • 2024-11-25陈小艺和丈夫没有共同语言 陈小艺的奇葩婚姻在演艺圈中有非常多的优秀演员,还有很多老戏骨,而这些老戏骨给我们留下过不少的经典作品而如今很多老戏骨随着年龄的增长,开始演一些"妈妈专业户""爸爸专业户"的电视剧今天我。