Android之ExpandableListView

来源:互联网 发布:csgo安卓软件 编辑:程序博客网 时间:2024/06/01 15:05

一、创建手风琴

要创建手风琴,有两种方式。

1.在XML中申明

 <ExpandableListView     android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:id="@+id/expand"    ></ExpandableListView>

2. 继承ExpandableListActivity


final String[] groups = { "家人", "朋友", "同事" };final String[][] children = { { "老爸", "老妈", "姐姐", "老婆" },{ "啊腾", "小永", "金文" }, { "陈老板", "书榕" } };ExpandableListAdapter adapter = new ExpandableListAdapter() {TextView getChildContent(){  AbsListView.LayoutParams lp = new AbsListView.LayoutParams(                     ViewGroup.LayoutParams.MATCH_PARENT, 64);             TextView textView = new TextView(MainApp.this);             textView.setLayoutParams(lp);             // Center the text vertically             textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);             // Set the text starting position             textView.setPadding(54, 0, 0, 0);//54表示textview本身与父对象的距离              textView.setTextSize(18);             return textView;}@Overridepublic View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent) {TextView view=getChildContent();view.setText(getChild(groupPosition, childPosition).toString());return view;}@Overridepublic View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent) {//LinearLayout layout=new LinearLayout(MainApp.this);/*设置按钮 * layout.setOrientation(0);ImageView logo = new ImageView(ExpandableListViewTest.this);logo.setImageResource(logos[groupPosition]);layout.addView(logo);*/TextView textview=getChildContent();textview.setText(getGroup(groupPosition).toString());//layout.addView(textview);return textview;}@Overridepublic int getChildrenCount(int groupPosition) {// TODO Auto-generated method stubreturn children[groupPosition].length;}@Overridepublic long getChildId(int groupPosition, int childPosition) {// TODO Auto-generated method stubreturn childPosition;}@Overridepublic Object getChild(int groupPosition, int childPosition) {// TODO Auto-generated method stubreturn children[groupPosition][childPosition];}@Overridepublic long getGroupId(int groupPosition) {// TODO Auto-generated method stubreturn groupPosition;}@Overridepublic int getGroupCount() {// TODO Auto-generated method stubreturn groups.length;}@Overridepublic Object getGroup(int groupPosition) {// TODO Auto-generated method stubreturn groups[groupPosition];}

其他重写的方法就略过了


expand = (ExpandableListView) findViewById(R.id.expand);expand.setAdapter(adapter);expand.setChildIndicator(getResources().getDrawable(R.drawable.home));//设置图标expand.setOnChildClickListener(new OnChildClickListener() {@Overridepublic boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id) {// TODO Auto-generated method stubToast.makeText(MainApp.this, children[groupPosition][childPosition], 1).show();return false;//isChildSelectable方法必须返回true}});





下载代码,点击这里