Android初学者—listView用法
我这次做了一个用android 获取当前本地文件、文件夹,并显示在listview上,点击文件夹,显示该文件夹下的文件和文件夹,希望各位大虾们能指出我的错误^__^
具体代码如下:
public class TestFileActivity extends ListActivity {
private ArrayList<String> items = null;
private ArrayList<String> paths = null;
private String rootPath = "/";
private TextView mPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPath = (TextView)findViewById(R.id.mPath);
mPath.setTextColor(Color.RED);
getFileDir(rootPath);
}
private void getFileDir(String filePath) {
mPath.setText(filePath);
items = new ArrayList<String>();
paths = new ArrayList<String>();
File file = new File(filePath);
File[] files = file.listFiles();
if(!filePath.equals(rootPath)) {
items.add("Back To " + rootPath);
paths.add(rootPath);
items.add("Back to ../");
paths.add(file.getParent());
}
for(File fileTemp :files) {
items.add(fileTemp.getName());
paths.add(fileTemp.getPath());
}
ArrayAdapter<String>adapter=new ArrayAdapter<String>(Test_fileActivity.this,R.layout.file_now,items);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(paths.get(position));
if(file.canRead()) {
if(file.isDirectory()) {
getFileDir(paths.get(position));
}else {
new AlertDialog.Builder(this)
.setTitle("Message")
.setMessage("["+file.getName() + "] is a file")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
else {
new AlertDialog.Builder(this)
.setTitle("Message")
.setMessage("操作无效")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/mPath"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
file_now.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="20px"
android:textSize="14sp"
>
</TextView>
感悟:
嘿嘿,是不是看了这么多代码很头疼哪?不过还好吧,这只是其中的一小部分而已。在这个小测试中,我学到了file.list()是获取文件下的列表,而file.canOpen()它是判断是否可以打开,最后的file.getParent()方法是返回上一级。俺学Android将近半年了,学的东西屈指可数。以后可要认真学习道上的真正开发哟!