ExpandableListView 可折叠的下拉listview
ExpandableListView用法如下
1.定义布局文件main.xml文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ExpandableListView android:childIndicator="@drawable/icon" android:id="@+id/el" android:layout_width="match_parent" android:layout_height="match_parent" > </ExpandableListView> </LinearLayout>
2.java代码如下
public class MainActivity extends Activity { final int[] images = { R.drawable.p, R.drawable.t, R.drawable.z }; final String[] names = { "人族", "虫族", "神族" }; final String[][] names_ = { { "特种兵", "警察", "城管" }, { "蚂蚁", "蚯蚓", "蜘蛛" }, { "大神", "玉皇大帝", "如来佛祖" } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test); ExpandableListView el = (ExpandableListView) findViewById(R.id.el); //此处使用ExpandableListAdapter的子类BaseExpandableListAdapter,否则使用父类会有很多方法需要重写 el.setAdapter(new BaseExpandableListAdapter() { @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } @Override public boolean hasStableIds() { return true; } //自定义一个方法,用于操作 父级/子级菜单中的文本 private TextView getTextView() { AbsListView.LayoutParams param = new AbsListView.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, 66);//定义列表每行的宽度以及高度 TextView tv = new TextView(MainActivity.this); tv.setLayoutParams(param); tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);//定义文本位置 tv.setPadding(60, 0, 0, 0);//居左60dp tv.setTextSize(24); return tv; } //获取父级视图--把图片和文本挂载到 线性布局上 @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { LinearLayout ll = new LinearLayout(MainActivity.this); ll.setOrientation(0); ImageView iv = new ImageView(MainActivity.this); iv.setImageResource(images[groupPosition]); ll.addView(iv); TextView tv = getTextView(); tv.setText(getGroup(groupPosition).toString()); ll.addView(tv); return ll; } @Override public long getGroupId(int groupPosition) { return groupPosition; } //获取父级菜单数量 @Override public int getGroupCount() { return names.length; } //获取每个父级对象 @Override public Object getGroup(int groupPosition) { return names[groupPosition]; } //获取下拉子菜单的数量 @Override public int getChildrenCount(int groupPosition) { return names_[groupPosition].length; } //显示下拉菜单项 @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { TextView tv = getTextView(); tv.setText(getChild(groupPosition, childPosition).toString()); return tv; } //获取下拉子菜单的id @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } //获取下拉子菜单中的 每个对象 @Override public Object getChild(int groupPosition, int childPosition) { return names_[groupPosition][childPosition]; } }); }