ExpandableListView控件基本使用

第一种用法:效果图如下:

1.三个布局文件:

main.xml  注意:  android:id="@id/android:list"不能写自己的

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

     <ExpandableListView
         android:id="@id/android:list"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         />

</RelativeLayout>

group.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" >

    <TextView
         android:id="@+id/textGroup"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:paddingLeft="40px"
         android:paddingTop="6px"
         android:paddingBottom="6px"
         android:layout_margin="20dp"
         android:textSize="15sp"
         android:textColor="#00cc00"
         android:text="我的好友"
     />

</LinearLayout>

child.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textChild"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:paddingBottom="10px"
        android:paddingLeft="60px"
        android:paddingTop="10px"
        android:layout_margin="20dp"
        android:textColor="#000000"
        android:text="hello"
        android:textSize="20sp" />

</LinearLayout>

2.MainActivity.java

package com.zhang.expandablelist;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.app.ExpandableListActivity;
import android.view.Menu;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;

public class MainActivity extends ExpandableListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* 创建二个一级条目标题
*/
Map<String, String> fatherTitle01 = new HashMap<String, String>();
        Map<String, String> fatherTitle02 = new HashMap<String, String>();
        fatherTitle01.put("group", "我的好友");
        fatherTitle02.put("group", "我的同事");

      //创建一级条目容器
        List<Map<String, String>> gruops = new ArrayList<Map<String,String>>();
        gruops.add(fatherTitle01);
        gruops.add(fatherTitle02);

      /**
       * 创建二级条目内容
       */
      //内容一
        Map<String, String> sontitle1 = new HashMap<String, String>();
        Map<String, String> sontitle2 = new HashMap<String, String>();
        Map<String, String> sontitle21 = new HashMap<String, String>();

        sontitle1.put("child", "android");
        sontitle2.put("child", "Java");
        sontitle21.put("child", "ios");
        //创建二级条目容器
       List<Map<String, String>> childs01 = new ArrayList<Map<String,String>>();
       childs01.add(sontitle1);
       childs01.add(sontitle2);
       childs01.add(sontitle21);

       //内容二
        Map<String, String> sontitle3 = new HashMap<String, String>();
        Map<String, String> sontitle4 = new HashMap<String, String>();
        Map<String, String> sontitle5 = new HashMap<String, String>();

        sontitle3.put("child", "刘备");
        sontitle4.put("child", "曹操");
        sontitle5.put("child", "孙权");

        List<Map<String, String>> childs02 = new ArrayList<Map<String,String>>();
        childs02.add(sontitle3);
        childs02.add(sontitle4);
        childs02.add(sontitle5);

       //存放两个内容, 以便显示在列表中
        List<List<Map<String, String>>> childs = new ArrayList<List<Map<String,String>>>();
        childs.add(childs01);
        childs.add(childs02);

       //创建ExpandableList的Adapter容器
        //参数: 1.上下文    2.一级集合 3.一级样式文件 4. 一级条目键值  5.一级显示控件名
        //   6. 二级集合 7. 二级样式 8.二级条目键值 9.二级显示控件名
        SimpleExpandableListAdapter sela = new SimpleExpandableListAdapter(
                this, gruops, R.layout.fathertitle, new String[]{"group"}, new int[]{R.id.textGroup},
               childs, R.layout.sontitle, new String[]{"child"}, new int[]{R.id.textChild}
                );

       //加入列表
        setListAdapter(sela);

}

//最后, 如果想响应各操作的话, 就要重载下面的方法
//列表内容按下
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
{
    // TODO Auto-generated method stub
    return super.onChildClick(parent, v, groupPosition, childPosition, id);
}

//二级标题按下
@Override
public boolean setSelectedChild(int groupPosition, int childPosition, boolean shouldExpandGroup)
{
    // TODO Auto-generated method stub
    return super.setSelectedChild(groupPosition, childPosition, shouldExpandGroup);
}

//一级标题按下
@Override
public void setSelectedGroup(int groupPosition)
{
    // TODO Auto-generated method stub
    super.setSelectedGroup(groupPosition);
}

}

第二种用法:效果图如下:

1.布局文件 look.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:id="@+id/expandableListView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        />
</LinearLayout>

2.LookActivity.java

package com.zhang.expandablelist;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;

public class LookActivity extends Activity {

	private List<String> GroupData;// 定义组数据
	private List<List<String>> ChildData;// 定义组中的子数据
	private ExpandableListView listView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.look);

		InitListDate();

		listView = (ExpandableListView) findViewById(R.id.expandableListView);
		listView.setAdapter(new ExpandableAdapter());
	}

	// 初始化组、子列表数据
	private void InitListDate() {
		//主列表数据
		GroupData = new ArrayList<String>();
		GroupData.add("国家");
		GroupData.add("风云人物");
		GroupData.add("武功秘籍");
		//子列表数据
		ChildData = new ArrayList<List<String>>();
		List<String> child1 = new ArrayList<String>();
		child1.add("中国");
		child1.add("美国");
		child1.add("日本 ");
		child1.add("韩国 ");
		child1.add("新加坡 ");

		List<String> child2 = new ArrayList<String>();
		child2.add("霍建华");
		child2.add("王祖蓝");
		child2.add("邓超");
		child2.add("郑凯");
		child2.add("刘亦菲");
		child2.add("章子怡");

		List<String> child3 = new ArrayList<String>();
		child3.add("降龙十八掌");
		child3.add("葵花宝典");
		child3.add("九阴真经");
		child3.add("太极拳");
		child3.add("凌波微步");
		ChildData.add(child1);
		ChildData.add(child2);
		ChildData.add(child3);
	}

	private class ExpandableAdapter extends BaseExpandableListAdapter {

		/**
		 * 取得与指定分组、指定子项目关联的数据. groupPosition 包含子视图的分组的位置. childPosition
		 * 指定的分组中的子视图的位置.
		 */
		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return ChildData.get(groupPosition).get(childPosition);
		}
        //取得一览中可以唯一识别子条目的 ID(包括分组ID和子条目ID).
//		可扩展列表要求每个条目 (分组条目和子条目)具有一个可以唯一识别列表中子条目和分组条目的ID.
//		该方法根据给定子条目ID和分组条目ID返回唯一识别ID.另外,如果 hasStableIds() 为真,该函数返回的ID必须是固定不变的.
		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return 0;
		}

		/**
		 * 取得显示给定分组给定子位置的数据用的视图.
		 * roupPosition:   包含要取得子视图的分组位置.
		 * childPosition:  分组中子视图(要返回的视图)的位置.
		 * isLastChild :   该视图是否为组中的最后一个视图.
		 * convertView:    如果可能,重用旧的视图对象 ,使用前你应该保证视图对象为非空,并且是否是合适的类型.如果该对象不能转换为可以正确显示数据的视图,该方法就创建新视图.不保证使用先前由
		                   getChildView(int, int,boolean, View, ViewGroup)创建的视图.
		 * parent : 该视图最终从属的父视图
		 */
		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			TextView mText = null;
			if (convertView != null) {
				mText = (TextView) convertView;
				mText.setText(ChildData.get(groupPosition).get(
						childPosition));
			} else {
				mText = createView(ChildData.get(groupPosition).get(
						childPosition));
			}
			// TextView textView=null;
			// if (convertView != null) {
			// convertView=LayoutInflater.from(getApplicationContext()).
			// inflate(R.layout.sontitle, null);
			// textView=(TextView) convertView.findViewById(R.id.textChild);
			//
			// textView.setText(ChildData.get(groupPosition).get(childPosition));
			// } else {
			// textView =
			// createView(ChildData.get(groupPosition).get(childPosition));
			// }
			return mText;
		}
         //取得指定分组的子元素数
		@Override
		public int getChildrenCount(int groupPosition) {
			return ChildData.get(groupPosition).size();
		}

		//取得与给定分组关联的数据.
		@Override
		public Object getGroup(int groupPosition) {
			return GroupData.get(groupPosition);
		}

		//指定分组的数据.
		@Override
		public int getGroupCount() {
			return GroupData.size();
		}
        //取得指定分组的ID.该组ID必须在组中是唯一的.必须不同于其他所有ID(分组及子项目的ID).
		@Override
		public long getGroupId(int groupPosition) {
			return 0;
		}

		/**
		 *
		 * 取得用于显示给定分组的视图. 这个方法仅返回分组的视图对象, 要想获取子元素的视图对象,
		              就需要调用 getChildView(int, int, boolean, View, ViewGroup).
		 *
		 * @param groupPosition:决定返回哪个视图的组位置 .
		 * @param isExpanded: 该组是展开状态还是收起状态 .
		 * @param convertView:如果可能,重用旧的视图对象.使用前你应该保证视图对象为非空,
		                                                         并且是否是合适的类型.如果该对象不能转换为可以正确显示数据的视图,该方法就创建新视图.
		                                                        不保证使用先前由 getGroupView(int, boolean,View, ViewGroup)创建的视图.
		 * @param parent:该视图最终从属的父视图.
		 * @return   指定位置相应的组视图.
		 *
		 */
		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			TextView mText = null;
			if (convertView != null) {
				mText = (TextView) convertView;
				mText.setText(GroupData.get(groupPosition));
			} else {
				mText = createView(GroupData.get(groupPosition));
			}
			// TextView textView=null;
			// if (convertView != null) {
			// convertView=LayoutInflater.from(getApplicationContext()).
			// inflate(R.layout.fathertitle, null);
			// textView=(TextView) convertView.findViewById(R.id.textGroup);
			//
			// textView.setText(GroupData.get(groupPosition));
			// }
			// else {
			// textView = createView(GroupData.get(groupPosition));
			// }
			return mText;
		}

        //是否指定分组视图及其子视图的ID对应的后台数据改变也会保持该ID.
		@Override
		public boolean hasStableIds() {
			return false;
		}

		//指定位置的子视图是否可选择.
		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return false;
		}

		// 创建TextView
		private TextView createView(String content) {
			AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT, 150);
			TextView mText = new TextView(LookActivity.this);
			mText.setLayoutParams(layoutParams);
			mText.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
			mText.setPadding(80, 0, 0, 0);
			mText.setText(content);
			return mText;
		}
	}
}

参考了:http://www.apkbus.com/android-124715-1-1.html

完整的Demo:http://download.csdn.net/detail/zhang106209/9529886

时间: 2024-08-30 16:36:26

ExpandableListView控件基本使用的相关文章

Android中ExpandableListView控件基本使用

本文採用一个Demo来展示Android中ExpandableListView控件的使用,如怎样在组/子ListView中绑定数据源.直接上代码例如以下: 程序结构图: layout文件夹下的 main.xml 文件源代码例如以下: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/a

ExpandableListView控件实现二级列表

效果图如下: 二级列表附有点击事件. 1.布局文件: 此处加了一个自定义的导航RelativeLayout,记得注activity的时候添加 android:theme="@style/Theme.AppCompat.Light.NoActionBar" 去掉自带的导航. 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="ht

android 伸缩控件ExpandableListView 展开失败的可能原因。

(原创)转载请声明出处http://www.cnblogs.com/linguanh/ 问题原型: ExpandableListView 展开失效. --------------------直接看结论请拉置 红线下------------------- 早在同年5月份的时候我写过一篇 自定义 ExpandableListView 收缩类的 博文,那时候我还没碰到这个问题, 一切很顺利, 入口:http://www.cnblogs.com/linguanh/p/4521257.html 直到今天,

Android 中常见控件的介绍和使用

1 TextView文本框 1.1 TextView类的结构 TextView 是用于显示字符串的组件,对于用户来说就是屏幕中一块用于显示文本的区域.TextView类的层次关系如下: java.lang.Object   ? android.view.View   ? android.widget.TextView 直接子类: Button, CheckedTextView, Chronometer, DigitalClock, EditText 间接子类: AutoCompleteTextV

Android控件第3类——AdapterView

AdapterView这一类控件的最大特点,在绝大多数的情况下,它们的数据都由Adapter的子类提供(有时可以在控件的entries属性上直接设置显示的数据). 调用AdapterView的setAdapter(Adapter)将控件与数据关联. 一.概述 AdapterView是一个抽象类,她继承了GroupView,所以它是一个容器类.它有三个子类:AbsListView.AbsSpinner.AdapterViewAnimator,这三个子类也都是抽象类.与之对应的Adapter是一个接

android listview和button,ImageButton等有事件的控件的总结

? 1 2 3 4 public ImageButton(Context context, AttributeSet attrs, int defStyle) {     super(context, attrs, defStyle);     setFocusable(true); } 在listview中(或者ExpandableListview),item的view会被进行特殊的处理,通过convertview可以减少解析xml文件,提高效率.但是如果你自己解析一次,然后用变量保存,那么只

android控件 下拉刷新pulltorefresh

外国人写的下拉刷新控件,我把他下载下来放在网盘,有时候访问不了github 支持各种控件下拉刷新 ListView.ViewPager.WevView.ExpandableListView.GridView.(Horizontal )ScrollView.Fragment上下左右拉动刷新,比下面johannilsson那个只支持ListView的强大的多.并且他实现的下拉刷新ListView在item不足一屏情况下也不会显示刷新提示,体验更好. 国内网盘地址:http://www.400gb.c

Android控件篇

Android中提供了丰富的UI空间.为了最大限度地发挥平台的性能.每个开发人员必须熟练掌握UI控件尤其是经常使用的UI控件.并能依据须要呈现的内容选择最恰当的控件. Android提供了XML配置和Java两种方式来配置控件属性. 通常.XML配置有利于扩展和多目标环境的适配,但因为添加了XML解析过程而使性能略低且无法动态变化,而Java方式尽管性能较好.但因为目标环境多变的Android设备而言,其扩展性通常无法满足项目的须要.在实际的开发工作中,开发人员可依据实际情况的须要及两种方法的优

Android02.常用布局及基本UI控件

一.Android学习API指南:[了解] 1. 应用的组成部分   App Components 1.1. 应用的基本原理    App Fundamentals 1.2. Activity      Activities 1.2.1. 片段    Fragments 1.2.2. 加载器     Loaders 1.2.3. 任务和返回堆    Tasks and Back Stack 1.3. Service服务   Services 1.3.1. 绑定服务     Bound Servi