Est-ce que quelqu'un connaît un dialogue de choix de fichier complet? Peut-être que vous pouvez filtrer tous les fichiers sauf ceux avec des extensions spécifiques?
Je n'ai rien trouvé assez léger pour être implémenté facilement dans l'un de mes projets. La seule autre option semble utiliser les intentions d'ouverture de OI FileManager, mais cela nécessite que l'utilisateur ait déjà installé le gestionnaire de fichiers.
Je serais reconnaissant si quelqu'un pouvait signaler un dialogue qui permettrait à l'utilisateur de parcourir des dossiers, de sélectionner un fichier et de renvoyer le chemin.
Il vous suffit de remplacer onCreateDialog
dans une activité.
//In an Activity
private String[] mFileList;
private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//");
private String mChosenFile;
private static final String FTYPE = ".txt";
private static final int DIALOG_LOAD_FILE = 1000;
private void loadFileList() {
try {
mPath.mkdirs();
}
catch(SecurityException e) {
Log.e(TAG, "unable to write on the sd card " + e.toString());
}
if(mPath.exists()) {
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
return filename.contains(FTYPE) || sel.isDirectory();
}
};
mFileList = mPath.list(filter);
}
else {
mFileList= new String[0];
}
}
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
switch(id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
if(mFileList == null) {
Log.e(TAG, "Showing file picker before loading the file list");
dialog = builder.create();
return dialog;
}
builder.setItems(mFileList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChosenFile = mFileList[which];
//you can do stuff with the file here too
}
});
break;
}
dialog = builder.show();
return dialog;
}
Merci schwiz pour l'idée! Voici la solution modifiée:
public class FileDialog {
private static final String PARENT_DIR = "..";
private final String TAG = getClass().getName();
private String[] fileList;
private File currentPath;
public interface FileSelectedListener {
void fileSelected(File file);
}
public interface DirectorySelectedListener {
void directorySelected(File directory);
}
private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
private final Activity activity;
private boolean selectDirectoryOption;
private String fileEndsWith;
/**
* @param activity
* @param initialPath
*/
public FileDialog(Activity activity, File initialPath) {
this(activity, initialPath, null);
}
public FileDialog(Activity activity, File initialPath, String fileEndsWith) {
this.activity = activity;
setFileEndsWith(fileEndsWith);
if (!initialPath.exists()) initialPath = Environment.getExternalStorageDirectory();
loadFileList(initialPath);
}
/**
* @return file dialog
*/
public Dialog createFileDialog() {
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(currentPath.getPath());
if (selectDirectoryOption) {
builder.setPositiveButton("Select directory", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, currentPath.getPath());
fireDirectorySelectedEvent(currentPath);
}
});
}
builder.setItems(fileList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String fileChosen = fileList[which];
File chosenFile = getChosenFile(fileChosen);
if (chosenFile.isDirectory()) {
loadFileList(chosenFile);
dialog.cancel();
dialog.dismiss();
showDialog();
} else fireFileSelectedEvent(chosenFile);
}
});
dialog = builder.show();
return dialog;
}
public void addFileListener(FileSelectedListener listener) {
fileListenerList.add(listener);
}
public void removeFileListener(FileSelectedListener listener) {
fileListenerList.remove(listener);
}
public void setSelectDirectoryOption(boolean selectDirectoryOption) {
this.selectDirectoryOption = selectDirectoryOption;
}
public void addDirectoryListener(DirectorySelectedListener listener) {
dirListenerList.add(listener);
}
public void removeDirectoryListener(DirectorySelectedListener listener) {
dirListenerList.remove(listener);
}
/**
* Show file dialog
*/
public void showDialog() {
createFileDialog().show();
}
private void fireFileSelectedEvent(final File file) {
fileListenerList.fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
public void fireEvent(FileSelectedListener listener) {
listener.fileSelected(file);
}
});
}
private void fireDirectorySelectedEvent(final File directory) {
dirListenerList.fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
public void fireEvent(DirectorySelectedListener listener) {
listener.directorySelected(directory);
}
});
}
private void loadFileList(File path) {
this.currentPath = path;
List<String> r = new ArrayList<String>();
if (path.exists()) {
if (path.getParentFile() != null) r.add(PARENT_DIR);
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
if (!sel.canRead()) return false;
if (selectDirectoryOption) return sel.isDirectory();
else {
boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
return endsWith || sel.isDirectory();
}
}
};
String[] fileList1 = path.list(filter);
for (String file : fileList1) {
r.add(file);
}
}
fileList = (String[]) r.toArray(new String[]{});
}
private File getChosenFile(String fileChosen) {
if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
else return new File(currentPath, fileChosen);
}
private void setFileEndsWith(String fileEndsWith) {
this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase() : fileEndsWith;
}
}
class ListenerList<L> {
private List<L> listenerList = new ArrayList<L>();
public interface FireHandler<L> {
void fireEvent(L listener);
}
public void add(L listener) {
listenerList.add(listener);
}
public void fireEvent(FireHandler<L> fireHandler) {
List<L> copy = new ArrayList<L>(listenerList);
for (L l : copy) {
fireHandler.fireEvent(l);
}
}
public void remove(L listener) {
listenerList.remove(listener);
}
public List<L> getListenerList() {
return listenerList;
}
}
Utilisez-le sur l’activité onCreate (l’option de sélection de répertoire est commentée):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
File mPath = new File(Environment.getExternalStorageDirectory() + "//DIR//");
fileDialog = new FileDialog(this, mPath, ".txt");
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
}
});
//fileDialog.addDirectoryListener(new FileDialog.DirectorySelectedListener() {
// public void directorySelected(File directory) {
// Log.d(getClass().getName(), "selected dir " + directory.toString());
// }
//});
//fileDialog.setSelectDirectoryOption(false);
fileDialog.showDialog();
}
J'ai créé FolderLayout
qui peut vous aider. Ceci lien m'a aidé
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:orientation="vertical" Android:layout_width="match_parent"
Android:layout_height="match_parent">
<TextView Android:id="@+id/path" Android:text="Path"
Android:layout_width="match_parent" Android:layout_height="wrap_content"></TextView>
<ListView Android:layout_width="fill_parent"
Android:layout_height="wrap_content" Android:id="@+id/list"></ListView>
</LinearLayout>
package com.testsample.activity;
public class FolderLayout extends LinearLayout implements OnItemClickListener {
Context context;
IFolderItemListener folderListener;
private List<String> item = null;
private List<String> path = null;
private String root = "/";
private TextView myPath;
private ListView lstView;
public FolderLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
this.context = context;
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.folderview, this);
myPath = (TextView) findViewById(R.id.path);
lstView = (ListView) findViewById(R.id.list);
Log.i("FolderView", "Constructed");
getDir(root, lstView);
}
public void setIFolderItemListener(IFolderItemListener folderItemListener) {
this.folderListener = folderItemListener;
}
//Set Directory for view at anytime
public void setDir(String dirPath){
getDir(dirPath, lstView);
}
private void getDir(String dirPath, ListView v) {
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if (!dirPath.equals(root)) {
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
path.add(file.getPath());
if (file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
Log.i("Folders", files.length + "");
setItemList(item);
}
//can manually set Item to display, if u want
public void setItemList(List<String> item){
ArrayAdapter<String> fileList = new ArrayAdapter<String>(context,
R.layout.row, item);
lstView.setAdapter(fileList);
lstView.setOnItemClickListener(this);
}
public void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory()) {
if (file.canRead())
getDir(path.get(position), l);
else {
//what to do when folder is unreadable
if (folderListener != null) {
folderListener.OnCannotFileRead(file);
}
}
} else {
//what to do when file is clicked
//You can add more,like checking extension,and performing separate actions
if (folderListener != null) {
folderListener.OnFileClicked(file);
}
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
onListItemClick((ListView) arg0, arg0, arg2, arg3);
}
}
Et une interface IFolderItemListener
pour ajouter quoi faire quand on clique sur un fileItem
public interface IFolderItemListener {
void OnCannotFileRead(File file);//implement what to do folder is Unreadable
void OnFileClicked(File file);//What to do When a file is clicked
}
Aussi un xml pour définir la ligne
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:id="@+id/rowtext" Android:layout_width="fill_parent"
Android:textSize="23sp" Android:layout_height="match_parent"/>
Dans votre 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="horizontal" Android:weightSum="1">
<com.testsample.activity.FolderLayout Android:layout_height="match_parent" layout="@layout/folderview"
Android:layout_weight="0.35"
Android:layout_width="200dp" Android:id="@+id/localfolders"></com.testsample.activity.FolderLayout></LinearLayout>
Dans votre activité,
public class SampleFolderActivity extends Activity implements IFolderItemListener {
FolderLayout localFolders;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
localFolders = (FolderLayout)findViewById(R.id.localfolders);
localFolders.setIFolderItemListener(this);
localFolders.setDir("./sys");//change directory if u want,default is root
}
//Your stuff here for Cannot open Folder
public void OnCannotFileRead(File file) {
// TODO Auto-generated method stub
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(
"[" + file.getName()
+ "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
//Your stuff here for file Click
public void OnFileClicked(File file) {
// TODO Auto-generated method stub
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
}
Importez les bibliothèques nécessaires. J'espère que cela vous aidera ...
Je cherchais moi-même un navigateur de fichiers/dossiers et ai décidé de créer une nouvelle activité de l'Explorateur (bibliothèque Android): https://github.com/vaal12/AndroidFileBrowser
L'application de test correspondant https://github.com/vaal12/FileBrowserTestApplication- est un exemple d'utilisation.
Permet de choisir des répertoires et des fichiers à partir de la structure de fichiers du téléphone.
Ajout au mélange: le gestionnaire de fichiers OI a une API publique enregistrée sur openintents.org
http://www.openintents.org/filemanager
http://www.openintents.org/action/org-openintents-action-pick-file/
J'ai implémenté le Samsung File Selector Dialog, il offre la possibilité d'ouvrir, de sauvegarder un fichier, de filtrer une extension de fichier et de créer un nouveau répertoire dans la même boîte de dialogue. Cela vaut la peine d'essayer Voici le Lien connectez-vous au site de développement Samsung pour afficher la solution