如何重新创建DialogFragment一个ListView [英] How to recreate a ListView in DialogFragment

查看:190
本文介绍了如何重新创建DialogFragment一个ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个DialogFragment用于浏览文件系统,它通过现在的作品真的很好。我刚刚得到一个问题。

该文件显示在一个ListView中,当用户选择了一个文件,这个事件是发送给已调用片段通过一个OnFileSelectedListener接口的活动。这是罚款的文件,但感觉不对送出的目录名的活动,那么破坏并重新创建片段,当所有应该发生的是,该片段应显示一个新的目录。这也使得整个Fragement disapearing然后reapearing这是不是真的很好,流畅。

此外利用碎片必须使用逻辑重新创建片段,这是远离不重复自己每一个活动。

因此​​,简而言之,有没有办法做到的片段中的列表视图的changeout?调用AlertDialog.Builder不止一次可悲的是不工作。

我的继承人DialogFragment。我希望这是确定后,整个事情:

 包de.fusionsystems.firmenlaufmonitor;进口的java.io.File;
进口的java.util.ArrayList;
进口java.util.Arrays中;进口android.app.Activity;
进口android.app.AlertDialog;
进口android.app.Dialog;
进口android.app.DialogFragment;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.content.DialogInterface.OnClickListener;
进口android.content.Shared preferences;
进口android.content.Shared preferences.Editor;
进口android.graphics.drawable.Drawable;
进口android.os.Bundle;
。进口的Andr​​oid preference preferenceManager。
进口android.util.Log;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.ArrayAdapter;
进口android.widget.TextView;公共类FileChooserFragment扩展DialogFragment {
    私人OnFileSelectedListener mCallback;    @覆盖
    公共对话框onCreateDialog(捆绑savedInstanceState){
        返回createDialog();
    }    私人AlertDialog createDialog(){
        //创建AlertDialog对象,并将其返回
        共享preferences选项= preferenceManager.getDefaultShared preferences(getActivity());
        ArrayList的<文件>文件= getFilesInDir(options.getString(的BaseDir,));
        ArrayList的<一个ListEntry> fileEntries =新的ArrayList<一个ListEntry>();        如果(!isBaseDir(options.getString(的BaseDir,))){
            fileEntries.add(新一个ListEntry(..,getResources()getDrawable(R.drawable.ic_folder)));
        }        对于(文件文件:文件){
            如果(file.isDirectory()){
                fileEntries.add(新一个ListEntry(file.getName(),getResources()getDrawable(R.drawable.ic_folder))。);
            }其他{
                如果(file.getName()。的endsWith(KML)){
                    fileEntries.add(新一个ListEntry(file.getName(),getResources()getDrawable(R.drawable.ic_file))。);
                }
            }
        }        最后FileAdapter适配器=新FileAdapter(getActivity(),fileEntries);
        OnClickListener clickListener =新OnClickListener(){
            @覆盖
            公共无效的onClick(DialogInterface对话,诠释它){
                字符串路径;
                共享preferences选项= preferenceManager.getDefaultShared preferences(getActivity());
                如果(adapter.getItem(所).name.equals()){
                    //导航回
                    路径= options.getString(的BaseDir,/);
                    路径= path.substring(0,path.length());
                    路径= path.substring(0,path.lastIndexOf(/));
                    !PATH = path.equals()?路径:(/);
                }其他{
                    PATH = options.getString(的BaseDir,);
                    路径+ =((path.equals(/))():(/?))+ adapter.getItem(它)。名称;
                }
                Log.d(路径,路径);
                编辑编辑= options.edit();
                文件dirTest =新的文件(路径);
                如果(dirTest.isDirectory()){
                    editor.putString(的BaseDir路径);
                    editor.commit();
                    //mCallback.onFileSelected();
                    // createDialog();
                    // *******************做正确的事这里***********************
                }其他{
                    mCallback.onFileSelected(路径);
                }
            }
        };
        //使用生成器类简单的对话框建设
        AlertDialog.Builder建设者=新AlertDialog.Builder(getActivity());
        builder.setAdapter(适配器,clickListener)
               .setNegativeButton(Abbrechen,新DialogInterface.OnClickListener(){
                   公共无效的onClick(DialogInterface对话,诠释的id){
                       解雇();
                   }
               });
        builder.setTitle(Datei瓦伦);
        返回builder.create();
        }    私人的ArrayList<文件> getFilesInDir(字符串DIR){
        文件夹=新的文件(目录);
        如果(!folder.exists()){
            文件夹=新的文件(/);
            如果(!folder.exists()){
                Log.e(FileBrowser,有些事情真的很腥);
            }
        }
        ArrayList的<文件>的fileList =新的ArrayList<文件>(Arrays.asList(folder.listFiles()));
        返回的fileList;
    }    私人布尔isBaseDir(字符串DIR){
        文件夹=新的文件(目录);
            如果(!folder.exists()){
                文件夹=新的文件(/);
                如果(!folder.exists()){
                    Log.e(FileBrowser,有些事情真的很腥);
                }
            }
        文件BASEDIR =新的文件(/);
        如果(folder.equals(BASEDIR)){
            返回true;
        }其他{
            返回false;
        }
    }    //集装箱活动必须实现此接口
    公共接口OnFileSelectedListener {
        公共无效onFileSelected(字符串文件);
    }    @覆盖
    公共无效onAttach(活动活动){
        super.onAttach(活动);
        //这将确保集装箱活动实施
        //回调接口。如果不是,它抛出一个异常
        尝试{
            mCallback =(OnFileSelectedListener)活性;
        }赶上(抛出ClassCastException E){
            抛出新ClassCastException异常(activity.toString()
                    +必须实现OnHeadlineSelectedListener);
        }
    }    类一个ListEntry {
        公共字符串名称;
        公众可绘制项目;        公众一个ListEntry(字符串名称,可绘制项){
           this.name =名称;
           this.item =项目;
        }
    }    类FileAdapter扩展ArrayAdapter<一个ListEntry> {        公共FileAdapter(上下文的背景下,ArrayList的<一个ListEntry> FileEntry的){
            超(背景下,R.layout.filechooser_list_item,FileEntry的);
        }        @覆盖
        公共查看getView(INT位置,查看convertView,父母的ViewGroup){
                一个ListEntry进入=的getItem(位置);
               //检查现有视图被重用,否则膨胀的观点
               如果(convertView == NULL){
                  convertView = LayoutInflater.from(的getContext())膨胀(R.layout.filechooser_list_item,父母,假的)。
               }
               数据人口//查询视图
               TextView的filechooserEntry =(TextView中)convertView.findViewById(R.id.filechooser_entry);
               //使用数据对象填充数据插入模板视图
               filechooserEntry.setText(entry.name);
               filechooserEntry.setCompoundDrawablesWithIntrinsicBounds(entry.item,NULL,NULL,NULL);
               //返回完成视图呈现在屏幕上
               返回convertView;
        }
    }
}


解决方案

下面是我的一个Filebrowser溶液作为DialogFragment。原来有方法来添加()删除()和干净()项到适配器,所以答案为最初的问题是真实的简单。最棘手的部分是prevent对话框中选择从列表项后,关闭。这个答案帮助了很多: http://stackoverflow.com/a/15619098/3960095 。这是我的工作code为今后游客:

 包de.yourCompany.yourProject;进口的java.io.File;
进口的java.util.ArrayList;
进口java.util.Arrays中;进口android.app.Activity;
进口android.app.AlertDialog;
进口android.app.Dialog;
进口android.app.DialogFragment;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.content.DialogInterface.OnClickListener;
进口android.content.Shared preferences;
进口android.content.Shared preferences.Editor;
进口android.graphics.drawable.Drawable;
进口android.os.Bundle;
。进口的Andr​​oid preference preferenceManager。
进口android.util.Log;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.AdapterView;
进口android.widget.AdapterView.OnItemClickListener;
进口android.widget.ArrayAdapter;
进口android.widget.TextView;公共类FileChooserFragment扩展DialogFragment {
    私人OnFileSelectedListener mCallback;    @覆盖
    公共对话框onCreateDialog(捆绑savedInstanceState){
         //创建AlertDialog对象,并将其返回
        最后FileAdapter适配器=新FileAdapter(getActivity(),新的ArrayList<一个ListEntry>());
        adapter.getFiles();
        OnClickListener clickListener =新OnClickListener(){
            @覆盖
            公共无效的onClick(DialogInterface对话,诠释它){
            //什么也不做这里prevent点击后解雇
            }
        };
        //使用生成器类简单的对话框建设
        AlertDialog.Builder建设者=新AlertDialog.Builder(getActivity());
        builder.setAdapter(适配器,clickListener)
               .setNegativeButton(Abbrechen,新DialogInterface.OnClickListener(){
                   公共无效的onClick(DialogInterface对话,诠释的id){
                   }
               });
        builder.setTitle(Datei瓦伦);
        最终AlertDialog theDialog = builder.show();
        theDialog.getListView()。setOnItemClickListener(新OnItemClickListener(){
            @覆盖
            公共无效onItemClick(适配器视图<>母公司,观景,INT位置,长的id){
                字符串路径;
                共享preferences选项= preferenceManager.getDefaultShared preferences(getActivity());
                如果(adapter.getItem(位置).name.equals()){
                    //导航回
                    路径= options.getString(的BaseDir,/);
                    路径= path.substring(0,path.length());
                    路径= path.substring(0,path.lastIndexOf(/));
                    !PATH = path.equals()?路径:(/);
                }其他{
                    //获取斜线权和向前导航
                    PATH = options.getString(的BaseDir,);
                    路径+ =((path.equals(/))():(/?))+ adapter.getItem(位置)。名称;
                }
                编辑编辑= options.edit();
                文件dirTest =新的文件(路径);
                如果(dirTest.isDirectory()){
                    editor.putString(的BaseDir路径);
                    editor.commit();
                    adapter.clear();
                    adapter.getFiles();
                }其他{
                    mCallback.onFileSelected(路径);
                    theDialog.dismiss();
                }            }
        });
        返回theDialog;
    }    私人布尔isBaseDir(字符串DIR){
        文件夹=新的文件(目录);
            如果(!folder.exists()){
                文件夹=新的文件(/);
                如果(!folder.exists()){
                    Log.wtf(FileBrowser,有些事情真的很腥);
                }
            }
        文件BASEDIR =新的文件(/);
        如果(folder.equals(BASEDIR)){
            返回true;
        }其他{
            返回false;
        }
    }    //集装箱活动必须实现此接口
    公共接口OnFileSelectedListener {
        公共无效onFileSelected(字符串文件);
    }    @覆盖
    公共无效onAttach(活动活动){
        super.onAttach(活动);
        //这将确保集装箱活动实施
        //回调接口。如果不是,它抛出一个异常
        尝试{
            mCallback =(OnFileSelectedListener)活性;
        }赶上(抛出ClassCastException E){
            抛出新ClassCastException异常(activity.toString()
                    +必须实现OnHeadlineSelectedListener);
        }
    }    类一个ListEntry {
        公共字符串名称;
        公众可绘制项目;        公众一个ListEntry(字符串名称,可绘制项){
           this.name =名称;
           this.item =项目;
        }
    }    类FileAdapter扩展ArrayAdapter<一个ListEntry> {        //只显示后缀为FILE_SUFFIX文件,请使用*显示所有文件;
        私有静态最后弦乐FILE_SUFFIX =.KML;        公共FileAdapter(上下文的背景下,ArrayList的<一个ListEntry> FileEntry的){
            超(背景下,R.layout.filechooser_list_item,FileEntry的);
        }        @覆盖
        公共查看getView(INT位置,查看convertView,父母的ViewGroup){
                一个ListEntry进入=的getItem(位置);
               //检查现有视图被重用,否则膨胀的观点
               如果(convertView == NULL){
                  convertView = LayoutInflater.from(的getContext())膨胀(R.layout.filechooser_list_item,父母,假的)。
               }
               数据人口//查询视图
               TextView的filechooserEntry =(TextView中)convertView.findViewById(R.id.filechooser_entry);
               //使用数据对象填充数据插入模板视图
               filechooserEntry.setText(entry.name);
               filechooserEntry.setCompoundDrawablesWithIntrinsicBounds(entry.item,NULL,NULL,NULL);
               //返回完成视图呈现在屏幕上
               返回convertView;
        }        私人FileAdapter的GetFiles(){
            共享preferences选项= preferenceManager.getDefaultShared preferences(getActivity());
            ArrayList的<文件>文件= getFilesInDir(options.getString(的BaseDir,));            如果(!isBaseDir(options.getString(的BaseDir,))){
                this.add(新一个ListEntry(..,getResources()getDrawable(R.drawable.ic_folder)));
            }            对于(文件文件:文件){
                如果(file.isDirectory()){
                    this.add(新一个ListEntry(file.getName(),getResources()getDrawable(R.drawable.ic_folder))。);
                }其他{
                    如果(file.getName()。的endsWith(FILE_SUFFIX)|| FILE_SUFFIX.equals(*)){
                        this.add(新一个ListEntry(file.getName(),getResources()getDrawable(R.drawable.ic_file))。);
                    }
                }
            }
        返回此;
        }        私人的ArrayList<文件> getFilesInDir(字符串DIR){
            文件夹=新的文件(目录);
            如果(!folder.exists()){
                文件夹=新的文件(/);
                如果(!folder.exists()){
                    Log.wtf(FileBrowser,有些事情真的很腥);
                }
            }
            ArrayList的<文件>的fileList;
            如果(folder.listFiles()!= NULL){
                的fileList =新的ArrayList<文件>(Arrays.asList(folder.listFiles()));
            }其他{
                的fileList =新的ArrayList<文件>();
            }
            返回的fileList;
        }
    }
}

和你的活动:

 公共类YourActivity扩展活动实现FileChooserFragment.OnFileSelectedListener {@覆盖
公共无效onFileSelected(字符串文件){
//做你想做的文件做
}//而徘徊无论你想要启动的片段:
FileChooserFragment fileFragment =新FileChooserFragment();
fileFragment.show(getFragmentManager(),文件选择);

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 file, this event is send to the Activity that has called the Fragment over an OnFileSelectedListener-Interface. This is fine for files, but it feels wrong to send out the directory names to the activity, then destroying and recreating the Fragment, when all that should happen is that the Fragment should show a new Directory. It also makes the whole Fragement disapearing and then reapearing which isn't really nice and smooth.

Furthermore every Activity using the Fragment has to use the logic for recreating the Fragment, which is far from "don't repeat yourself".

So, in short, is there a way to do a changeout of the Listview within the Fragment? Calling the AlertDialog.Builder more than once sadly doesn't work.

Heres my DialogFragment. I hope it's ok to post the whole thing:

package de.fusionsystems.firmenlaufmonitor;

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.ArrayAdapter;
import android.widget.TextView;

public class FileChooserFragment extends DialogFragment {
    private OnFileSelectedListener mCallback;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return createDialog();
    }

    private AlertDialog createDialog(){
        // Create the AlertDialog object and return it
        SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(getActivity());
        ArrayList<File> files = getFilesInDir(options.getString("BaseDir", ""));
        ArrayList<ListEntry> fileEntries = new ArrayList<ListEntry>();

        if (!isBaseDir(options.getString("BaseDir", ""))){
            fileEntries.add(new ListEntry("..", getResources().getDrawable( R.drawable.ic_folder)));
        }

        for (File file : files){            
            if (file.isDirectory()){
                fileEntries.add(new ListEntry(file.getName(),getResources().getDrawable(R.drawable.ic_folder)));
            }else{
                if (file.getName().endsWith(".kml")){
                    fileEntries.add(new ListEntry(file.getName(),getResources().getDrawable( R.drawable.ic_file)));
                }
            }   
        }

        final FileAdapter adapter = new FileAdapter(getActivity(), fileEntries);
        OnClickListener clickListener = new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String path;
                SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(getActivity());
                if (adapter.getItem(which).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 {
                    path = options.getString("BaseDir", "");
                    path += ((path.equals("/"))?(""):("/"))+adapter.getItem(which).name;
                }
                Log.d("Path", path);
                Editor editor = options.edit();
                File dirTest = new File(path);
                if (dirTest.isDirectory()){
                    editor.putString("BaseDir", path);
                    editor.commit();
                    //mCallback.onFileSelected("");
                    //createDialog();
                    //*******************DO THE RIGHT THING HERE***********************
                }else{
                    mCallback.onFileSelected(path);
                }
            }
        };
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setAdapter(adapter, clickListener)
               .setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       dismiss();
                   }
               });
        builder.setTitle("Datei wählen");
        return builder.create();
        }

    private ArrayList<File> getFilesInDir(String dir) {
        File folder = new File(dir);
        if (!folder.exists()){
            folder = new File("/");
            if (!folder.exists()){
                Log.e("FileBrowser","Something's really fishy");
            }
        }
        ArrayList<File> fileList = new ArrayList<File>(Arrays.asList(folder.listFiles()));
        return fileList;
    }

    private boolean isBaseDir(String dir) {
        File folder = new File(dir);
            if (!folder.exists()){
                folder = new File("/");
                if (!folder.exists()){
                    Log.e("FileBrowser","Something's really fishy");
                }
            }
        File baseDir = new File("/");
        if (folder.equals(baseDir)){
            return true;
        }else{
            return false;
        }
    }

    // Container Activity must implement this interface
    public interface OnFileSelectedListener {
        public void onFileSelected(String file);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try { 
            mCallback = (OnFileSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    class ListEntry {
        public String name;
        public Drawable item ;

        public ListEntry(String name, Drawable item) {
           this.name = name;
           this.item = item;
        }
    }

    class FileAdapter extends ArrayAdapter<ListEntry>{

        public FileAdapter(Context context, ArrayList<ListEntry> fileEntry) {
            super(context, R.layout.filechooser_list_item,fileEntry);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent){
                ListEntry entry = getItem(position);    
               // Check if an existing view is being reused, otherwise inflate the view
               if (convertView == null) {
                  convertView = LayoutInflater.from(getContext()).inflate(R.layout.filechooser_list_item, parent, false);
               }
               // Lookup view for data population
               TextView filechooserEntry = (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 screen
               return convertView;
        }   
    }
}

解决方案

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: http://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;

public class FileChooserFragment extends DialogFragment{
    private OnFileSelectedListener mCallback;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
         // Create the AlertDialog object and return it
        final FileAdapter adapter = new FileAdapter(getActivity(), new ArrayList<ListEntry>());             
        adapter.getFiles();     
        OnClickListener clickListener = new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            //do nothing here to prevent dismiss after click    
            }
        };
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setAdapter(adapter, clickListener)
               .setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                   }
               });
        builder.setTitle("Datei wählen");
        final AlertDialog theDialog = builder.show();
        theDialog.getListView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String path;
                SharedPreferences options = 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;
                }
                Editor editor = options.edit();
                File dirTest = new File(path);
                if (dirTest.isDirectory()){
                    editor.putString("BaseDir", path);
                    editor.commit();
                    adapter.clear();
                    adapter.getFiles();
                }else{
                    mCallback.onFileSelected(path);
                    theDialog.dismiss();
                }

            }
        });
        return theDialog;
    }

    private boolean isBaseDir(String dir) {
        File folder = new File(dir);
            if (!folder.exists()){
                folder = new File("/");
                if (!folder.exists()){
                    Log.wtf("FileBrowser","Something's really fishy");
                }
            }
        File baseDir = new File("/");
        if (folder.equals(baseDir)){
            return true;
        }else{
            return false;
        }
    }

    // Container Activity must implement this interface
    public interface OnFileSelectedListener {
        public void onFileSelected(String file);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try { 
            mCallback = (OnFileSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    class ListEntry {
        public String name;
        public Drawable item ;

        public ListEntry(String name, Drawable item) {
           this.name = name;
           this.item = item;
        }
    }

    class FileAdapter extends ArrayAdapter<ListEntry>{

        //show only files with the suffix FILE_SUFFIX, use "*" to show all files;
        private static final String FILE_SUFFIX = ".kml";

        public FileAdapter(Context context, ArrayList<ListEntry> fileEntry) {
            super(context, R.layout.filechooser_list_item,fileEntry);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent){
                ListEntry entry = getItem(position);    
               // Check if an existing view is being reused, otherwise inflate the view
               if (convertView == null) {
                  convertView = LayoutInflater.from(getContext()).inflate(R.layout.filechooser_list_item, parent, false);
               }
               // Lookup view for data population
               TextView filechooserEntry = (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 screen
               return convertView;
        }   

        private FileAdapter getFiles() {
            SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(getActivity());
            ArrayList<File> files = getFilesInDir(options.getString("BaseDir", ""));

            if (!isBaseDir(options.getString("BaseDir", ""))){
                this.add(new ListEntry("..", getResources().getDrawable( R.drawable.ic_folder)));
            }

            for (File file : files){            
                if (file.isDirectory()){
                    this.add(new ListEntry(file.getName(),getResources().getDrawable(R.drawable.ic_folder)));
                }else{
                    if (file.getName().endsWith(FILE_SUFFIX)||FILE_SUFFIX.equals("*")){
                        this.add(new ListEntry(file.getName(),getResources().getDrawable(R.drawable.ic_file)));
                    }
                }   
            }
        return this;
        }

        private ArrayList<File> getFilesInDir(String dir) {
            File folder = new File(dir);
            if (!folder.exists()){
                folder = new File("/");
                if (!folder.exists()){
                    Log.wtf("FileBrowser","Something's really fishy");
                }
            }
            ArrayList<File> fileList;
            if (folder.listFiles()!=null){
                fileList = new ArrayList<File>(Arrays.asList(folder.listFiles()));
            }else{
                fileList = new ArrayList<File>();
            }
            return fileList;
        }
    }
}

and in your Activity:

public class YourActivity extends Activity implements FileChooserFragment.OnFileSelectedListener{

@Override
public void onFileSelected(String file) {
//Do whatever you want to do with the files
}

// And whereever you want to start the Fragment: 
FileChooserFragment fileFragment = new FileChooserFragment();
fileFragment.show(getFragmentManager(), "fileChooser"); 

这篇关于如何重新创建DialogFragment一个ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆