How To Recreate A Listview In Dialogfragment
I'm writing a DialogFragment for browsing the filesystem, which works really nice by now. I just got one Problem. The files are shown in an ListView, and when the user selects a f
Solution 1:
Here's my solution for a Filebrowser as a DialogFragment. It turns out there are methods to add() remove() and clean() items to the adapter, so the answer to the initial question was real simple. The tricky part was to prevent the Dialog from closing after selecting a List item. This answer helped a lot: https://stackoverflow.com/a/15619098/3960095. Here's my working code for future visitors:
package de.yourCompany.yourProject;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;
publicclassFileChooserFragmentextendsDialogFragment{
private OnFileSelectedListener mCallback;
@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState) {
// Create the AlertDialog object and return itfinalFileAdapteradapter=newFileAdapter(getActivity(), newArrayList<ListEntry>());
adapter.getFiles();
OnClickListenerclickListener=newOnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
//do nothing here to prevent dismiss after click
}
};
// Use the Builder class for convenient dialog construction
AlertDialog.Builderbuilder=newAlertDialog.Builder(getActivity());
builder.setAdapter(adapter, clickListener)
.setNegativeButton("Abbrechen", newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int id) {
}
});
builder.setTitle("Datei wählen");
finalAlertDialogtheDialog= builder.show();
theDialog.getListView().setOnItemClickListener(newOnItemClickListener() {
@OverridepublicvoidonItemClick(AdapterView<?> parent, View view, int position, long id) {
String path;
SharedPreferencesoptions= PreferenceManager.getDefaultSharedPreferences(getActivity());
if (adapter.getItem(position).name.equals("..")){
//navigate back
path = options.getString("BaseDir", "/");
path=path.substring(0, path.length());
path=path.substring(0,path.lastIndexOf("/"));
path = !path.equals("")?path:("/");
}else {
//get the Slashes right and navigate forward
path = options.getString("BaseDir", "");
path += ((path.equals("/"))?(""):("/"))+adapter.getItem(position).name;
}
Editoreditor= options.edit();
FiledirTest=newFile(path);
if (dirTest.isDirectory()){
editor.putString("BaseDir", path);
editor.commit();
adapter.clear();
adapter.getFiles();
}else{
mCallback.onFileSelected(path);
theDialog.dismiss();
}
}
});
return theDialog;
}
privatebooleanisBaseDir(String dir) {
Filefolder=newFile(dir);
if (!folder.exists()){
folder = newFile("/");
if (!folder.exists()){
Log.wtf("FileBrowser","Something's really fishy");
}
}
FilebaseDir=newFile("/");
if (folder.equals(baseDir)){
returntrue;
}else{
returnfalse;
}
}
// Container Activity must implement this interfacepublicinterfaceOnFileSelectedListener {
publicvoidonFileSelected(String file);
}
@OverridepublicvoidonAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented// the callback interface. If not, it throws an exceptiontry {
mCallback = (OnFileSelectedListener) activity;
} catch (ClassCastException e) {
thrownewClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
classListEntry {
public String name;
public Drawable item ;
publicListEntry(String name, Drawable item) {
this.name = name;
this.item = item;
}
}
classFileAdapterextendsArrayAdapter<ListEntry>{
//show only files with the suffix FILE_SUFFIX, use "*" to show all files;privatestaticfinalStringFILE_SUFFIX=".kml";
publicFileAdapter(Context context, ArrayList<ListEntry> fileEntry) {
super(context, R.layout.filechooser_list_item,fileEntry);
}
@Overridepublic View getView(int position, View convertView, ViewGroup parent){
ListEntryentry= getItem(position);
// Check if an existing view is being reused, otherwise inflate the viewif (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.filechooser_list_item, parent, false);
}
// Lookup view for data populationTextViewfilechooserEntry= (TextView) convertView.findViewById(R.id.filechooser_entry);
// Populate the data into the template view using the data object
filechooserEntry.setText(entry.name);
filechooserEntry.setCompoundDrawablesWithIntrinsicBounds(entry.item, null, null, null);
// Return the completed view to render on screenreturn convertView;
}
private FileAdapter getFiles() {
SharedPreferencesoptions= PreferenceManager.getDefaultSharedPreferences(getActivity());
ArrayList<File> files = getFilesInDir(options.getString("BaseDir", ""));
if (!isBaseDir(options.getString("BaseDir", ""))){
this.add(newListEntry("..", getResources().getDrawable( R.drawable.ic_folder)));
}
for (File file : files){
if (file.isDirectory()){
this.add(newListEntry(file.getName(),getResources().getDrawable(R.drawable.ic_folder)));
}else{
if (file.getName().endsWith(FILE_SUFFIX)||FILE_SUFFIX.equals("*")){
this.add(newListEntry(file.getName(),getResources().getDrawable(R.drawable.ic_file)));
}
}
}
returnthis;
}
private ArrayList<File> getFilesInDir(String dir) {
Filefolder=newFile(dir);
if (!folder.exists()){
folder = newFile("/");
if (!folder.exists()){
Log.wtf("FileBrowser","Something's really fishy");
}
}
ArrayList<File> fileList;
if (folder.listFiles()!=null){
fileList = newArrayList<File>(Arrays.asList(folder.listFiles()));
}else{
fileList = newArrayList<File>();
}
return fileList;
}
}
}
and in your Activity:
publicclassYourActivityextendsActivityimplementsFileChooserFragment.OnFileSelectedListener{
@OverridepublicvoidonFileSelected(String file) {
//Do whatever you want to do with the files
}
// And whereever you want to start the Fragment: FileChooserFragmentfileFragment=newFileChooserFragment();
fileFragment.show(getFragmentManager(), "fileChooser");
Post a Comment for "How To Recreate A Listview In Dialogfragment"