如何在ListView中显示文件的arraylist

时间:2014-04-01 14:52:20

标签: android listview android-listview arraylist android-sdcard

我使用此功能在ArrayList中显示TextView,这将显示SDCard中的所有目录和文件,但我想改用ListView。我该怎么做才能在ListView中显示目录和SD卡的所有文件?

方法getfile读取所有文件和目录,并将ArrayList类对象添加为文件列表:

private File root;
private ArrayList<File> fileList = new ArrayList<File>();
private LinearLayout view;
private EditText filename;
private Button search;
private TextView allfiles,searchfile;
Spannable txt;
boolean check=false;
ListView l;
String [] strarray;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    l=(ListView)findViewById(R.id.listView1);
    view = (LinearLayout) findViewById(R.id.view);``
    filename=(EditText)findViewById(R.id.filename);
    allfiles=(TextView)findViewById(R.id.allfiles);
    searchfile=(TextView)findViewById(R.id.searchfile);
    search=(Button)findViewById(R.id.search);

    String path=Environment.getExternalStorageDirectory().toString();
    root = new File(path);

    getfile(root);
    for (int i = 0; i < fileList.size(); i++) 
    {
        if (fileList.get(i).isDirectory()) 
        {
            txt=new SpannableString(fileList.get(i).getName());
            txt.setSpan(new ForegroundColorSpan(Color.RED), 0, txt.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            allfiles.append(txt);
            allfiles.append("\n");
        }
        // if file than show in default color
        else
        {
        allfiles.append(fileList.get(i).getName());
        allfiles.append("\n");
        allfiles.setPadding(5, 5, 5, 5);

        }
    }

getfile方法显示SD卡上的所有目录和文件:

public ArrayList<File> getfile(File dir) 
{
    File listFile[] = dir.listFiles();

    if (listFile != null && listFile.length > 0)
    {
        for (int i = 0; i < listFile.length; i++) 
        {

            if (listFile[i].isDirectory())
            {
                fileList.add(listFile[i]);
                getfile(listFile[i]);// recursive calling to scan hole sdcard


            }
            else 
            {
                //condition to check file exists or not if yes add it to searchfile text view written below
                if(listFile[i].getName().toString().substring(0,listFile[i].getName().toString().indexOf(".")).compareToIgnoreCase(filename.getText().toString())==0)
                {
                    searchfile.append(listFile[i].getName());
                    searchfile.append("\n"); 
                    check=true;
                }
                fileList.add(listFile[i]);

            }

        }

return fileList;

1 个答案:

答案 0 :(得分:0)

首先了解Listview及其关联的methods,然后参考以下帖子How to display files on the SD card in a ListView?来回答您的问题。

为了搜索列表视图中的项目,您需要按照以下步骤进行操作:

  1. 将TextWatcher添加到EditText。TextView#addTextChangedListener
  2. 在listview BaseAdapter中实施Filterable界面
  3. 有关详情,请参阅List View Filter Android。希望这会帮助你开始:)