这ListView真是麻烦,一个小小的FileBrowser废了将近2天。看来自己的功力还需要加强。
做FileBrowser中遇到几个ListView问题总结一下。
1、自定义样式
ListView其实和Asp.net里面的Repeater有点像,但是不同的是项的内容可以用一个layout文件来套用,这个比较有意思,毕竟刚开始研究android姑且叫它自定义样式吧,正好我考虑着后期给FileBrowser写个换肤的功能,有这个东西就比较easy了。
首先需要这样的layout文件:
res/layout/imagelist.xml
<? xml version="1.0" encoding="UTF-8" ?>< RelativeLayout xmlns:android ="http://schemas.android.com/apk/res/android"android:id ="@+id/RelativeLayout01" android:layout_width ="fill_parent"android:layout_height ="wrap_content" android:paddingBottom ="4dip"android:paddingLeft ="12dip" android:paddingRight ="12dip" >< ImageView android:paddingTop ="12dip" android:layout_width ="50dip"android:layout_height ="50dip" android:id ="@+id/img" android:layout_alignParentLeft ="true" />< TextView android:text ="TextView01" android:layout_height ="wrap_content"android:textSize ="20dip" android:layout_width ="fill_parent"layout_centerVertical ="true" android:layout_centerInParent ="true"android:paddingLeft ="50dip" android:gravity ="clip_vertical"android:id ="@+id/file" />< CheckBox android:id ="@+id/cbSelect" android:layout_width ="wrap_content"android:focusable ="false" <!-- 这个没有的话会让ListView的内容无没点击,因为CheckBox获得焦点的优先级比ListView要高,不明白为什么要这样设计,事实是并没有点到CheckBox它也会把下面的ListView的项完全挡住-->android:layout_height ="wrap_content" android:layout_alignParentRight ="true"android:layout_centerVertical ="true" ></ CheckBox ></ RelativeLayout >
然后在onCreate中用下面的方法即可将layout里套用的东西显示出来
ListView lv = (ListView) findViewById(R.id.lvFile);
LinearLayout llFile = (LinearLayout) findViewById(R.id.llfiles);
SimpleAdapter listAdapter = new SimpleAdapter( this , GetFiles(),
R.layout.imagelist, new String[] { " img " , " file " }, new int [] {
R.id.img, R.id.file });
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setAdapter(listAdapter);
GetFile方法:
public List < Map < String, Object >> GetFiles() {
File file = new File(currentPath);
File[] fileList = file.listFiles();
files.clear();
Map < String, Object > mapBack = new HashMap < String, Object > ();
mapBack.put( " img " , R.drawable.folder);
mapBack.put( " file " , " .. " );
mapBack.put( " checked " , false );
Arrays.sort(fileList, ComparorFactory.CreateComparator( " FileName " ));
files.add(mapBack);
for (File f : fileList) {
Map < String, Object > map = new HashMap < String, Object > ();
if ( ! f.canRead())
continue ;
map.put( " img " , IconFactory.getIcon(f));
map.put( " file " , f.getName());
files.add(map);
}
return files;
}
现在能看到这样的界面,但是文件夹不能向上,怎么办,
private View getHeaderView() {
LayoutInflater rl = getLayoutInflater();
View row = rl.inflate(R.layout.imagelist, null , false );
CheckBox cb = (CheckBox) row.findViewById(R.id.cbSelect);
cb.setVisibility(CheckBox.INVISIBLE);
ImageView img = (ImageView) row.findViewById(R.id.img);
img.setImageResource(R.drawable.folder);
TextView txt = (TextView) row.findViewById(R.id.file);
txt.setText( " .. " );
return row;
}