来酷狗面试的时候面试官问过我,如果要显示/隐藏ListView的某个Item项目中的某些内容,我会怎么做。
我当时的回答是,做一个布局文件里面把所有要用到的项目都写上,哪个不需要了就将他设为gone就可以了。
今天在看代码的时候发现,原来有ExpandableListView这个东西,很明显,我当时的回答有点太浅层次了。
ExpandableListView见名知意,专门用于实现可收缩的ListView,即其中的item有父子item。实现的效果大致如下,使用ExpandableListView来做父子Item实现起来相当容易。
ExpandableListView使用ExpandableListAdapter来做为其适配器,ExpandableListAdapter也有其基础适配器BaseExpandableListAdapter;
具体代码如下:
package com.wallj.listviewdemo;
import android.R.color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
public class ExpandableListViewDemo extends Activity {
ExpandableListView mExpdListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expandable_list_view_demo);
mExpdListView = (ExpandableListView) findViewById(R.id.exListView);
mExpdListView.setAdapter(mExAdapter);
}
ExpandableListAdapter mExAdapter = new BaseExpandableListAdapter() {
private String[] generalsTypes = new String[] { "魏", "蜀", "吴" };
private String[][] generals = new String[][] {
{ "夏侯惇", "甄姬", "许褚", "郭嘉", "司马懿", "杨修" },
{ "马超", "张飞", "刘备", "诸葛亮", "黄月英", "赵云" },
{ "吕蒙", "陆逊", "孙权", "周瑜", "孙尚香" }
};
@Override
public boolean isChildSelectable(int arg0, int arg1) {
return false;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getGroupView(int arg0, boolean arg1, View arg2, ViewGroup arg3) {
if(arg2 == null){
arg2 = new TextView(ExpandableListViewDemo.this);
((TextView)arg2).setTextSize(30);
}
((TextView)arg2).setText(generalsTypes[arg0]);
return arg2;
}
@Override
public long getGroupId(int arg0) {
return arg0;
}
@Override
public int getGroupCount() {
return generalsTypes.length;
}
@Override
public Object getGroup(int arg0) {
return generalsTypes[arg0];
}
@Override
public int getChildrenCount(int arg0) {
return generals[arg0].length;
}
@Override
public View getChildView(int arg0, int arg1, boolean arg2, View arg3,
ViewGroup arg4) {
if(arg3 == null){
arg3 = new TextView(ExpandableListViewDemo.this);
}
((TextView)arg3).setText(generals[arg0][arg1]);
return arg3;
}
@Override
public long getChildId(int arg0, int arg1) {
return arg1;
}
@Override
public Object getChild(int arg0, int arg1) {
return generals[arg0][arg1];
}
};
}