Android中ExpandableListView的用法实例
本文实例讲述了Android中ExpandableListView的用法,ExpandableListView是android中可以实现下拉list的一个控件,具体的实现方法如下:
首先:在layout的xml文件中定义一个ExpandableListView
<LinearLayout android:id="@+id/linearLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" androidrientation="vertical" > <ExpandableListView android:id="@+id/expandableListView" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>
定义两个List,用来存放控件中Group/Child中的String
privateList<String>groupArray; privateList<List<String>>childArray;
对这两个List进行初始化,并插入一些数据
groupArray=newArrayList<String>(); childArray=newArrayList<List<String>>(); groupArray.add("第一行"); groupArray.add("第二行"); List<String>tempArray=newArrayList<String>(); tempArray.add("第一条"); tempArray.add("第二条"); tempArray.add("第三条"); for(intindex=0;index<groupArray.size();++index) { childArray.add(tempArray); }
定义ExpandableListView的Adapter
//ExpandableListView的Adapter publicclassExpandableAdapterextendsBaseExpandableListAdapter { Activityactivity; publicExpandableAdapter(Activitya) { activity=a; } publicObjectgetChild(intgroupPosition,intchildPosition) { returnchildArray.get(groupPosition).get(childPosition); } publiclonggetChildId(intgroupPosition,intchildPosition) { returnchildPosition; } publicintgetChildrenCount(intgroupPosition) { returnchildArray.get(groupPosition).size(); } publicViewgetChildView(intgroupPosition,intchildPosition, booleanisLastChild,ViewconvertView,ViewGroupparent) { Stringstring=childArray.get(groupPosition).get(childPosition); returngetGenericView(string); } //groupmethodstub publicObjectgetGroup(intgroupPosition) { returngroupArray.get(groupPosition); } publicintgetGroupCount() { returngroupArray.size(); } publiclonggetGroupId(intgroupPosition) { returngroupPosition; } publicViewgetGroupView(intgroupPosition,booleanisExpanded, ViewconvertView,ViewGroupparent) { Stringstring=groupArray.get(groupPosition); returngetGenericView(string); } //ViewstubtocreateGroup/Children'sView publicTextViewgetGenericView(Stringstring) { //LayoutparametersfortheExpandableListView AbsListView.LayoutParamslayoutParams=newAbsListView.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT,64); TextViewtext=newTextView(activity); text.setLayoutParams(layoutParams); //Centerthetextvertically text.setGravity(Gravity.CENTER_VERTICAL|Gravity.LEFT); //Setthetextstartingposition text.setPadding(36,0,0,0); text.setText(string); returntext; } publicbooleanhasStableIds() { returnfalse; } publicbooleanisChildSelectable(intgroupPosition,intchildPosition) { returntrue; } }
最后,给定义好的ExpandableListView添加上Adapter
ExpandableListViewexpandableListView=(ExpandableListView)findViewById(R.id.expandableListView); expandableListView.setAdapter(newExpandableAdapter(Main.this));
希望本文所述对大家的Android程序设计有所帮助。