2014-04-01 49 views
0

我正在使用此功能在TextView中顯示ArrayList,它將顯示SDCard中的所有目錄和文件,但我想用ListView代替。我應該怎麼做才能在ListView中顯示目錄和SD卡的所有文件?如何在ListView中顯示文件的陣列列表

方法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; 

回答