先看下效果图:
第一个是展开的效果,剩下两个是关闭的效果。
包含三个文件,一个 java,另一个重写的BaseExpandableListAdapter,还有一个布局文件
java代码:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ExpandableListView s = ((ExpandableListView) findViewById(R.id.expandableListView1));
eda adapter = new eda(this);
s.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
adaptert代码:
public class eda extends BaseExpandableListAdapter {
private Context cxt;
int[] logos = new int[] { R.drawable.z1, R.drawable.z2, R.drawable.z4 };
String[] gt = new String[] { "组1", "组2", "组3" };
String[][] arms = new String[][] { { "狂战士", "雨雪卖身", "asdas" },
{ "高于掐", "神奇的猴子", "不神奇啊" }, { "天才的啥", "士大夫", "q32" } };
public eda(Context ctx) {
// TODO Auto-generated constructor stub
this.cxt = ctx;
}
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return arms[groupPosition][childPosition];
}
public long getChildId(int arg0, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
public View getChildView(int groupPosition, int childPosition,
boolean isExpanded, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView t = new TextView(cxt);
t.setPadding(50, 0, 0, 0);
t.setText(getChild(groupPosition, childPosition).toString());
return t;
}
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return arms[groupPosition].length;
}
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return gt[groupPosition];
}
public int getGroupCount() {
// TODO Auto-generated method stub
return gt.length;
}
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View converView, ViewGroup parent) {
// TODO Auto-generated method stub
LinearLayout ll = new LinearLayout(cxt);
ll.setOrientation(0);
ImageView logo = new ImageView(cxt);
logo.setImageResource(logos[groupPosition]);
ll.addView(logo);
TextView tt = new TextView(cxt);
tt.setText(getGroup(groupPosition).toString());
ll.addView(tt);
return ll;
}
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
public boolean isChildSelectable(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
}
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ExpandableListView
android:id="@+id/expandableListView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:childIndicator="@drawable/z3" >
</ExpandableListView>
</LinearLayout>