android选择文件(安卓系统文件夹详解)
程序员文章站
2024-02-08 22:14:52
废话没有,先看效果第一步:创建mainactivityimport android.app.activity;import android.content.context;import android...
废话没有,先看效果
第一步:创建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() {
@override
public 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.png和_16_folder.png
下一篇: C#中图片、二进制与字符串的相互转换方法