转载请注明出处: http://blog.csdn.net/like_program/article/details/52549435
在做项目的时候,想在 ExpandableListView 中嵌套一个 GridView,在实现的过程中,遇到了不少坑,所以写篇博客记录一下,也顺便帮助下和我一样的新手。
我一直觉得,再多的文字,再多的代码片段,都不如写个小 Demo 更直观,所以在以后的博客中,我都尽量用小 Demo 来讲解,也给出源码。
先上一张最终效果图:
打开 Android Studio,我们新建一个 ExpandableListViewTest 项目,在项目中新建两个包(package), 分别命名为 activity 和 adapter,然后将 Android Studio 默认创建的 MainActivity 拖入 activity 包中。
为了让项目运行起来看上去更美观,我们用 Theme 主题,修改 AndroidManifest.xml 中的 application 下的 android:theme 属性,修改为 @android:style/Theme
,
修改后的 AndroidManifest.xml 代码如下所示:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@android:style/Theme" >
<activity android:name=".activity.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
修改了主题后,我们再修改下 MainActivity.java 文件,MainActivity 默认继承自 AppCompatActivity ,我们把 AppCompatActivity 修改为 Activity,让 MainActivity 继承 Activity,这样等会项目才能正常运行。
我们先来写一下布局文件,既然我们想在 ExpandableListView 中嵌套一个 GridView,那么首先我们应该写一个 ExpandableListView
activity_main.xml 代码如下所示:
<?xml version="1.0" encoding="utf-8"?>
<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=".activity.MainActivity">
<ExpandableListView
android:id="@+id/expandableList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:childDivider="@drawable/separator"
android:divider="@drawable/separator"/>
</RelativeLayout>
布局文件非常简单,在布局中只放置了一个 ExpandableListView,并设置了各组之间的分割线和各组子项之间的分割线,分割线是一张图片。接下来我们就要在 MainActivity 中实例化 ExpandableListView 的布局,并准备好 ExpandableListView 要显示的数据,然后把数据传入 ExpandableListView 的适配器,这样才能把 ExpandableListView 显示出来。
MainActivity.java 代码如下所示:
package com.example.expandablelistviewtest.activity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ExpandableListView;
import com.example.expandablelistviewtest.R;
import com.example.expandablelistviewtest.adapter.MyExpandableListViewAdapter;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private ExpandableListView expandableListView;
/**
* 每个分组的名字的集合
*/
private List<String> groupList;
/**
* 每个分组下的每个子项的 GridView 数据集合
*/
private List<String> itemGridList;
/**
* 所有分组的所有子项的 GridView 数据集合
*/
private List<List<String>> itemList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acti