Android开发如何获取我所点击的文件的地址
发布网友
发布时间:2022-04-29 23:47
我来回答
共1个回答
热心网友
时间:2022-06-26 08:46
跟java里获取当前本地文件、文件夹,,点击文件夹,显示该文件夹下的文件和文件夹,是没有区别的啊,唯一就是在文件夹上添加监听事件,然后获取对象就是了……
activity :
package com.hundsun.zhoujl.android;
import java.io.File;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Test_fileActivity extends ListActivity {
private ArrayList<String> items = null;
private ArrayList<String> paths = null;
private String rootPath = "/";
private TextView mPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPath = (TextView)findViewById(R.id.mPath);
mPath.setTextColor(Color.RED);
getFileDir(rootPath);
}
private void getFileDir(String filePath) {
mPath.setText(filePath);
items = new ArrayList<String>();
paths = new ArrayList<String>();
File file = new File(filePath);
File[] files = file.listFiles();
if(!filePath.equals(rootPath)) {
items.add("Back To " + rootPath);
paths.add(rootPath);
items.add("Back to ../");
paths.add(file.getParent());
}
for(File fileTemp :files) {
items.add(fileTemp.getName());
paths.add(fileTemp.getPath());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Test_fileActivity.this,R.layout.file_now,items);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(paths.get(position));
if(file.canRead()) {
if(file.isDirectory()) {
getFileDir(paths.get(position));
}else {
new AlertDialog.Builder(this)
.setTitle("Message")
.setMessage("["+file.getName() + "] is a file")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}else {
new AlertDialog.Builder(this)
.setTitle("Message")
.setMessage("权限不足~")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/mPath"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
file_now.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="20px"
android:textSize="14sp"
>
</TextView>