----Main.java
public class Main extends Activity { private TextView textView; private Button button; private ListView listView; public File currentParentFile; public File[] currentFiles; public static String sdcardDir ; static { try { //sd卡的路径 sdcardDir = Environment.getExternalStorageDirectory().getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.textView1); button = (Button) findViewById(R.id.button1); listView = (ListView) findViewById(R.id.listView1); File root = new File(sdcardDir); if(root.exists()){ currentParentFile = root; currentFiles = root.listFiles(); updateListView(currentFiles); } listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { if (currentFiles[position].isFile()) return; File[] tmp = currentFiles[position].listFiles(); if (tmp == null || tmp.length == 0) { Toast.makeText(Main.this, "当前路径无效,或没有文件", Toast.LENGTH_SHORT).show(); } else { currentParentFile = currentFiles[position]; currentFiles = tmp; updateListView(currentFiles); } } }); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { if (!currentParentFile.getCanonicalPath().equals( sdcardDir)) { currentParentFile = currentParentFile.getParentFile(); currentFiles = currentParentFile.listFiles(); updateListView(currentFiles); } else return; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } private void updateListView(File[] files) { List
布局文件----main.xml
效果:
listview的每一条的布局:
---listitem.xml
demo运行效果: