【安卓笔记】ExpandableListView的使用

实现效果:

即可伸展的ListView

其实跟普通的ListView使用没啥区别,只是ListView改为了ExpandableListView,另外适配器由BaseAdapter也换成了BaseExpandableListAdapter。

步骤:

1.编写布局文件。

分为三个,分别是主布局,group分组布局,group item布局:

activity_main.xml:

<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="com.example.expandablelistviewdemo.MainActivity" >
    <ExpandableListView
        android:id="@+id/elv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="#000"
        android:dividerHeight="2.5dp"
        android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorLeft" >
    </ExpandableListView>
</RelativeLayout>

list_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/listTitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
        android:paddingTop="10dp"
        android:textColor="#A4C739" />
</LinearLayout>

list_item.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/expandedListItem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
        android:paddingTop="10dp" />
</LinearLayout>

2.编写适配器代码:

package com.example.expandablelistviewdemo;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class MyExpandableListAdapter extends BaseExpandableListAdapter
{
	private Context mContext;
	private List<String> expandableListTitle;
	private HashMap<String, List<String>> expandableListDetail;

	public MyExpandableListAdapter(List<String> expandableListTitle,HashMap<String,List<String>> expandableListDetail,Context mContext)
	{
		this.expandableListDetail = expandableListDetail;
		this.expandableListTitle = expandableListTitle;
		this.mContext = mContext;
	}

	@Override
	public int getGroupCount()//分组数
	{
		return this.expandableListTitle.size();
	}
	@Override
	public int getChildrenCount(int groupPosition)//分组内的item数
	{
		return this.expandableListDetail.get(expandableListTitle.get(groupPosition)).size();
	}
	@Override
	public Object getGroup(int groupPosition)//获取分组数据
	{
		return this.expandableListTitle.get(groupPosition);
	}
	@Override
	public Object getChild(int groupPosition, int childPosition)//获取第几分组第几个item的数据
	{
		return this.expandableListDetail.get(this.expandableListTitle.get(groupPosition)).get(childPosition);
	}
	@Override
	public long getGroupId(int groupPosition)
	{
		return groupPosition;
	}
	@Override
	public long getChildId(int groupPosition, int childPosition)
	{
		return childPosition;
	}
	@Override
	public boolean hasStableIds()
	{
		return false;
	}
	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent)
	{
		String data = this.expandableListTitle.get(groupPosition);
		if(convertView == null)
		{
			convertView = View.inflate(mContext,R.layout.list_group, null);
		}
		TextView tv = (TextView) convertView.findViewById(R.id.listTitle);
		tv.setText(data);
		return convertView;
	}
	@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent)
	{
//		String data = this.expandableListDetail.get(this.expandableListTitle.get(groupPosition)).get(childPosition);
		String data = (String) this.getChild(groupPosition, childPosition);
		if(convertView == null)
		{
			convertView = View.inflate(mContext, R.layout.list_item, null);
		}
		TextView tv = (TextView) convertView.findViewById(R.id.expandedListItem);
		tv.setText(data);
		return convertView;
	}
	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition)
	{
		return true;
	}
}

可以看到,适配器中有两个getView的方法,分别去构造group和child的view。

3.构造数据源

package com.example.expandablelistviewdemo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ExpandableListDataPump
{
	public static HashMap<String, List<String>> getData()
	{
		HashMap<String, List<String>> expandableListDetail = new HashMap<String, List<String>>();
		List<String> technology = new ArrayList<String>();
		technology.add("Beats sued for noise-cancelling tech");
		technology.add("Wikipedia blocks US Congress edits");
		technology.add("Google quizzed over deleted links");
		technology.add("Nasa seeks aid with Earth-Mars links");
		technology.add("The Good, the Bad and the Ugly");
		List<String> entertainment = new ArrayList<String>();
		entertainment.add("Goldfinch novel set for big screen");
		entertainment.add("Anderson stellar in Streetcar");
		entertainment.add("Ronstadt receives White House honour");
		entertainment.add("Toronto to open with The Judge");
		entertainment.add("British dancer return from Russia");
		List<String> science = new ArrayList<String>();
		science.add("Eggshell may act like sunblock");
		science.add("Brain hub predicts negative events");
		science.add("California hit by raging wildfires");
		science.add("Rosetta's comet seen in close-up");
		science.add("Secret of sandstone shapes revealed");
		expandableListDetail.put("TECHNOLOGY NEWS", technology);
		expandableListDetail.put("ENTERTAINMENT NEWS", entertainment);
		expandableListDetail.put("SCIENCE & ENVIRONMENT NEWS", science);
		return expandableListDetail;
	}
}

4.编写主界面的代码

package com.example.expandablelistviewdemo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;
public class MainActivity extends Activity
{
	private ExpandableListView elv = null;
	private MyExpandableListAdapter adapter = null;

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

		elv = (ExpandableListView) findViewById(R.id.elv);

		final HashMap<String,List<String>> itemData = ExpandableListDataPump.getData();
		final List<String> title = new ArrayList<String>(itemData.keySet());
		adapter = new MyExpandableListAdapter(title,itemData,this);

		elv.setAdapter(adapter);

		//去掉箭头
//		elv.setGroupIndicator(null);

		//收缩
		elv.setOnGroupCollapseListener(new OnGroupCollapseListener()
		{

			@Override
			public void onGroupCollapse(int groupPosition)
			{
				Toast.makeText(MainActivity.this,title.get(groupPosition)+" group collapse..... ", 0).show();
			}
		});
		//伸展
		elv.setOnGroupExpandListener(new OnGroupExpandListener()
		{
			@Override
			public void onGroupExpand(int groupPosition)
			{
				Toast.makeText(MainActivity.this,title.get(groupPosition)+" group expand... ", 0).show();
			}
		});
		//子条目点击
		elv.setOnChildClickListener(new OnChildClickListener()
		{
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id)
			{
				Toast.makeText(MainActivity.this,itemData.get(title.get(groupPosition)).get(childPosition)+" click", 0).show();
				return false;
			}
		});

	}
}

ok,完成。

这里需要注意的是ExpandableListView有多个监听器,group收缩和伸展以及子条目点击等等,按需监听。

另外,默认情况下显示的时候有个箭头,你可以通过setGroupIndicator方法设置你需要的标识。

源码地址:https://github.com/Rowandjj/ExpandableListViewDemo

时间: 2024-08-10 23:27:12

【安卓笔记】ExpandableListView的使用的相关文章

【安卓笔记】抽屉式布局----DrawerLayout

效果如下: DrawerLayout来自support.v4包,所以不用考虑兼容性问题.其次,这种布局类似风靡一时的侧滑菜单,但是比侧滑菜单轻巧许多. 下面介绍这种布局的使用方式. 1.在你的项目中导入support.v4包. 2.编辑一个布局,根节点为android.support.v4.widget.DrawerLayout,此节点下只允许有两个子节点,第一个为将来主页面的内容,第二个节点即为"抽屉"内容,通常是一个ListView.比如: <android.support.

【安卓笔记】通过发送特定的短信远程控制手机

实现效果: 1.发送指令#*location*#,可以远程获取到手机的地理位置(经纬度),并以短信的形式返回. 2.发送指令#*locknow*#,可以远程锁屏并设置锁屏密码. 实现原理: 1.注册广播接受者,监听手机收到的短信,并对符合要求的特定短信进行拦截和处理. 2.通过LocationManager获取地理位置. 3.使用DevicePolicyManager实现锁屏.设置锁屏密码等操作. 步骤: 1.创建一个可以获取地理位置的工具类: package cn.edu.chd.mobile

【安卓笔记】仿猎豹清理大师波浪效果

先来看效果: 实现方式----->自定义控件 核心代码: package com.example.wavedemo1; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.os.Handler; import

【安卓笔记】在拨号界面通过拨打指定号码来启动某个秘密界面

方案说明: 1.通过注册广播接收者监听用户拨打电话操作: 2.当用户拨打电话时,广播接收者接收到号码,并与指定的"暗号"对比,若匹配,则启动某个界面并且终止用户拨打电话操作. 实现: 1.在清单文件中配置广播接收者,并添加权限: <receiver android:name="cn.edu.chd.mobilesafe.receiver.CallPhoneReceiver" > <intent-filter android:priority=&qu

【安卓笔记】快速开发设置界面-----PreferenceActivity

通常app都会有一个设置界面,如下: 通常做法是自己定义布局,然后在代码里面添加响应函数,并将结果保存到Sharedpreferences中. android给我们提供了PreferenceActivity来简化开发设置界面. 你只需这样做: 1.创建一个类继承PreferenceActivity,并导入设置界面布局: package com.example.preferenceactivitydemo1; import android.os.Bundle; import android.pre

【安卓笔记】切换图片(底部带有小点效果)

下面我们要实现这样的效果: 我们将采用两种方式实现这种效果: 1.使用ViewPager: 思路:ViewPager提供左右滑动图片操作的支持,下方小点在代码中动态创建,整个布局采用FrameLayout. 先看布局: <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" and

Xamrin开发安卓笔记(二)

安装篇 Xamrin开发安卓笔记(一) 昨天调理一天AAPT.EXE 被推出的问题(错误代码 error MSB6006: "aapt.exe" exited with code -1073741819),纠结一天到底是什么原因,寝食难安,后来想通了可能是安卓模拟器的原因.今早换了一个安卓SDK,到现在没出现AAPT的错误. 并且可以可视化布局(之前可视化布局很丑陋).然后接着写,暂时抛弃vs2015,因为2015的BUG直接影响我编写的感觉,所以先用vs2013 update4继续写

【安卓笔记】带自定义属性的view控件

开发中经常需要自定义view控件或者组合控件,某些控件可能需要一些额外的配置.比如自定义一个标题栏,你可能需要根据不同尺寸的手机定制不同长度的标题栏,或者更常见的你需要配置标题栏的背景,这时候,你就会考虑到你写的view的扩展性问题,通常情况下,我们可以为这个自定义的标题栏加上一些setXXX方法,供外界调用,设置其颜色.长度等属性.但是我们都知道,在使用系统控件时,我们大多数情况下并不需要在代码中配置控件,而仅仅只需在布局文件中对控件宽.高.颜色等进行配置,这样做的好处就将UI与业务逻辑解耦,

【安卓笔记】检测服务是否运行

/** * 判断服务是否后台运行 * * @param context * Context * @param className * 判断的服务名字 * @return true 在运行 false 不在运行 */ public static boolean isServiceRun(Context mContext, String className) { boolean isRun = false; ActivityManager activityManager = (ActivityMan

【安卓笔记】单机版手机归属地查询

既然是单机版,那么必然是查询本地数据库了,所以我们得准备一个离线数据库文件(下载地址:http://download.csdn.net/detail/rowandjj/7660979). 步骤: 1.创建一个工具类打开数据库: package cn.edu.chd.mobilesafe.db.dao; import android.database.sqlite.SQLiteDatabase; public class AddressDao { public static SQLiteDatab