我有一个问题。我有一个应用程序,在应用程序的目录中使用mkdir在辅助活动中添加文件夹。
fun createFolder (v: View){
//Make folder
val folderName = addFolderField.text.toString()
val dir1 = this.getDir("picture", Context.MODE_PRIVATE) //this is to make directory as well
File(dir1, folderName).mkdir()
finish()
假设我创建了多个文件夹。然后如何在我的主要活动中使用基本适配器显示文件夹列表
答案 0 :(得分:0)
创建activity_list_files.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView android:id="@android:id/list" android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
和ListFileActivity
public class ListFileActivity extends ListActivity {
private String path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_files);
// Use the current directory as title
path = "/";
if (getIntent().hasExtra("path")) {
path = getIntent().getStringExtra("path");
}
setTitle(path);
// Read all files sorted into the values-array
List values = new ArrayList();
File dir = new File(path);
if (!dir.canRead()) {
setTitle(getTitle() + " (inaccessible)");
}
String[] list = dir.list();
if (list != null) {
for (String file : list) {
if (!file.startsWith(".")) {
values.add(file);
}
}
}
Collections.sort(values);
// Put the data into the list
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_2, android.R.id.text1, values);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String filename = (String) getListAdapter().getItem(position);
if (path.endsWith(File.separator)) {
filename = path + filename;
} else {
filename = path + File.separator + filename;
}
if (new File(filename).isDirectory()) {
Intent intent = new Intent(this, ListFileActivity.class);
intent.putExtra("path", filename);
startActivity(intent);
} else {
Toast.makeText(this, filename + " is not a directory", Toast.LENGTH_LONG).show();
}
}
}
其中path
是您创建文件夹的完整目录路径。活动显示此路径中的所有文件。如果我们切换路径,我们切换到显示给定目录中所有文件的新活动。
另外,请确保在清单中添加uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
。