ExpandableListView实例

ExpandableListView实例先来看效果图:demo中有三个groupitem和多个childitem,groupitem包括一个指示器,一个标题和一个按钮。childitem包括一个图片,一个标题和一个按钮。先来实现布局文件1activity_main.xml

大家好,又见面了,我是你们的朋友全栈君。

先来看效果图:
这里写图片描述
demo中有三个group item和多个child item,group item包括一个指示器,一个标题和一个按钮。child item包括一个图片,一个标题和一个按钮。先来实现布局文件
1 activity_main.xml

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

    <ExpandableListView  android:id="@+id/expandlist" android:layout_width="match_parent" android:layout_height="match_parent" android:cacheColorHint="#00000000" android:divider="@android:color/white" android:dividerHeight="1dp" />

</RelativeLayout>

group布局,groupitem.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="50dp" android:orientation="horizontal" android:gravity="center_vertical" >
    <RelativeLayout android:layout_width="match_parent" android:layout_height="50dp">
        <ImageView android:id="@+id/img_indicator" android:layout_width="32dp" android:layout_height="32dp" android:layout_marginLeft="15dp" android:layout_centerVertical="true"/>
        <TextView android:id="@+id/tv_group_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_centerVertical="true" android:layout_toRightOf="@id/img_indicator" android:text="zhang san" android:textSize="16sp"/>
        <Button  android:id="@+id/btn_group_function" android:focusable="false" android:clickable="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_alignParentRight="true" android:layout_marginRight="20dp" android:gravity="right" android:background="@drawable/btn_bg_menu" />
    </RelativeLayout>


</LinearLayout>

child布局文件childitem.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="50dp" android:paddingStart="8dp" android:gravity="center_vertical" android:orientation="horizontal">

    <RelativeLayout android:layout_width="match_parent" android:layout_height="50dp">
        <ImageView android:id="@+id/img_child" android:layout_width="50dp" android:layout_height="50dp" android:layout_marginLeft="20dp" android:layout_centerVertical="true"/>
        <TextView android:id="@+id/tv_child_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_centerVertical="true" android:layout_toRightOf="@id/img_child" android:text="xiangjiao" android:textSize="16sp"/>
        <Button  android:id="@+id/btn_child_function" android:focusable="false" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_alignParentRight="true" android:layout_marginRight="20dp" android:gravity="right" android:background="@drawable/btn_bg_menu" />
    </RelativeLayout>

</LinearLayout>

2 由于每一个child子项中的图片和标题都不一样,因此我们要新建一个Java bean类来描述每一个子项内容
新建ChildItem.java

package com.example.model;

public class ChildItem {
    private String title;//子项显示的文字
    private int markerImgId;//每个子项的图标

    public ChildItem(String title, int markerImgId)
    {
        this.title = title;
        this.markerImgId = markerImgId;

    }

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public int getMarkerImgId() {
        return markerImgId;
    }
    public void setMarkerImgId(int markerImgId) {
        this.markerImgId = markerImgId;
    }


}

3 如果要将自定义的数据在ExpandableListView上显示出来,我们必须定义一个适配器

package com.example.expandablelistdemo;

import java.util.List;
import java.util.Map;

import com.example.model.ChildItem;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/** * ExpandListView的适配器,继承自BaseExpandableListAdapter * */
public class MyBaseExpandableListAdapter extends BaseExpandableListAdapter implements OnClickListener { 
   

    private Context mContext;
    private List<String> groupTitle;
    //子项是一个map,key是group的id,每一个group对应一个ChildItem的list
    private Map<Integer, List<ChildItem>> childMap;
    private Button groupButton;//group上的按钮

    public MyBaseExpandableListAdapter(Context context, List<String> groupTitle, Map<Integer, List<ChildItem>> childMap) {
        this.mContext = context;
        this.groupTitle = groupTitle;
        this.childMap = childMap;
    }
    /* * Gets the data associated with the given child within the given group */
    @Override
    public Object getChild(int groupPosition, int childPosition) {
        //我们这里返回一下每个item的名称,以便单击item时显示
        return childMap.get(groupPosition).get(childPosition).getTitle();
    }
    /* * 取得给定分组中给定子视图的ID. 该组ID必须在组中是唯一的.必须不同于其他所有ID(分组及子项目的ID) */
    @Override
    public long getChildId(int groupPosition, int childPosition) {      
        return childPosition;
    }
    /* * Gets a View that displays the data for the given child within the given group */
    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, 
            ViewGroup parent) {
        ChildHolder childHolder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.childitem, null);
            childHolder = new ChildHolder();
            childHolder.childImg = (ImageView) convertView.findViewById(R.id.img_child);
            childHolder.childText = (TextView) convertView.findViewById(R.id.tv_child_text);
            convertView.setTag(childHolder);
        }else {
            childHolder = (ChildHolder) convertView.getTag();
        }
        childHolder.childImg.setBackgroundResource(childMap.get(groupPosition).get(childPosition).getMarkerImgId());
        childHolder.childText.setText(childMap.get(groupPosition).get(childPosition).getTitle());

        return convertView;
    }

    /* * 取得指定分组的子元素数 */
    @Override
    public int getChildrenCount(int groupPosition) {
        // TODO Auto-generated method stub
        return childMap.get(groupPosition).size();
    }

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

    /** * 取得分组数 */
    @Override
    public int getGroupCount() {
        return groupTitle.size();
    }

    /** * 取得指定分组的ID.该组ID必须在组中是唯一的.必须不同于其他所有ID(分组及子项目的ID) */
    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }
    /* *Gets a View that displays the given group *return: the View corresponding to the group at the specified position */
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        GroupHolder groupHolder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.groupitem, null);
            groupHolder = new GroupHolder();
            groupHolder.groupImg = (ImageView) convertView.findViewById(R.id.img_indicator);
            groupHolder.groupText = (TextView) convertView.findViewById(R.id.tv_group_text);
            convertView.setTag(groupHolder);
        }else {
            groupHolder = (GroupHolder) convertView.getTag();
        }
        if (isExpanded) {
            groupHolder.groupImg.setBackgroundResource(R.drawable.downarrow);
        }else {
            groupHolder.groupImg.setBackgroundResource(R.drawable.rightarrow);
        }
        groupHolder.groupText.setText(groupTitle.get(groupPosition));

        groupButton = (Button) convertView.findViewById(R.id.btn_group_function);
        groupButton.setOnClickListener(this);
        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        // Indicates whether the child and group IDs are stable across changes to the underlying data
        return true;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        // Whether the child at the specified position is selectable
        return true;
    }
    /** * show the text on the child and group item */ 
    private class GroupHolder { 
   
        ImageView groupImg;
        TextView groupText;
    }
    private class ChildHolder { 
   
        ImageView childImg;
        TextView childText;
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_group_function:
            Log.d("MyBaseExpandableListAdapter", "你点击了group button");           
        default:
            break;
        }

    }   
}

4 MainActivity.java

package com.example.expandablelistdemo;

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

import com.example.model.ChildItem;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;

public class MainActivity extends Activity { 
   
    private ExpandableListView expandList;
    private List<String> groupData;//group的数据源
    private Map<Integer, List<ChildItem>> childData;//child的数据源
    private MyBaseExpandableListAdapter myAdapter;

    final int CONTEXT_MENU_GROUP_DELETE = 0;//添加上下文菜单时每一个菜单项的item ID
    final int CONTEXT_MENU_GROUP_RENAME = 1;
    final int CONTEXT_MENU_CHILD_EDIT = 2;
    final int CONTEXT_MENU_CHILD_DELETE = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initDatas();
        initView();
        initEvents();
    }
    /** * group和child子项的数据源 */
    private void initDatas() {

        groupData = new ArrayList<String>();
        groupData.add("红色水果");
        groupData.add("黄色水果");
        groupData.add("其他水果");

        List<ChildItem> childItems = new ArrayList<ChildItem>();
        ChildItem childData1 = new ChildItem("苹果", R.drawable.apple_pic);
        childItems.add(childData1);
        ChildItem childData2 = new ChildItem("樱桃", R.drawable.cherry_pic);
        childItems.add(childData2);
        ChildItem childData3 = new ChildItem("草莓", R.drawable.strawberry_pic);
        childItems.add(childData3);

        List<ChildItem> childItems2 = new ArrayList<ChildItem>();
        ChildItem childData4 = new ChildItem("香蕉", R.drawable.banana_pic);
        childItems2.add(childData4);
        ChildItem childData5 = new ChildItem("芒果", R.drawable.mango_pic);
        childItems2.add(childData5);
        ChildItem childData6 = new ChildItem("橘子", R.drawable.orange_pic);
        childItems2.add(childData6);
        ChildItem childData7 = new ChildItem("梨子", R.drawable.pear_pic);
        childItems2.add(childData7);

        List<ChildItem> childItems3 = new ArrayList<ChildItem>();
        ChildItem childData8 = new ChildItem("葡萄", R.drawable.grape_pic);
        childItems3.add(childData8);
        ChildItem childData9 = new ChildItem("西瓜", R.drawable.watermelon_pic);
        childItems3.add(childData9);

        childData = new HashMap<Integer, List<ChildItem>>();
        childData.put(0, childItems);
        childData.put(1, childItems2);
        childData.put(2, childItems3);

        myAdapter = new MyBaseExpandableListAdapter(this, groupData, childData);
    }

    private void initView() {
        expandList = (ExpandableListView) findViewById(R.id.expandlist);
        //在drawable文件夹下新建了indicator.xml,下面这个语句也可以实现group伸展收缩时的indicator变化
        //expandList.setGroupIndicator(this.getResources().getDrawable(R.drawable.indicator));
        expandList.setGroupIndicator(null);//这里不显示系统默认的group indicator
        expandList.setAdapter(myAdapter);
        registerForContextMenu(expandList);//给ExpandListView添加上下文菜单 
    }
    private void initEvents() {
        //child子项的单击事件
        expandList.setOnChildClickListener(new OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                    int groupPosition, int childPosition, long id) {
                Toast.makeText(MainActivity.this, "你单击了:"  
                        +myAdapter.getChild(groupPosition, childPosition), Toast.LENGTH_SHORT).show();  
                return true;
            }
        }); 

    }
    /* * 添加上下文菜单 */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {

        super.onCreateContextMenu(menu, v, menuInfo);
        ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo)menuInfo;
        int type = ExpandableListView.getPackedPositionType(info.packedPosition);
        if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
            menu.setHeaderTitle("Options");
            menu.add(0, CONTEXT_MENU_GROUP_DELETE, 0, "删除");
            menu.add(0, CONTEXT_MENU_GROUP_RENAME, 0, "重命名");
        }
        if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
            menu.setHeaderTitle("Options");
            menu.add(1, CONTEXT_MENU_CHILD_EDIT, 0, "编辑");
            menu.add(1, CONTEXT_MENU_CHILD_DELETE, 0, "删除");
        }

    }
    /* * 每个菜单项的具体点击事件 */
    @Override
    public boolean onContextItemSelected(MenuItem item) {

     ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo)item.getMenuInfo();
     switch (item.getItemId()) {
        case CONTEXT_MENU_GROUP_DELETE:
            Toast.makeText(this, "这是group的删除", Toast.LENGTH_SHORT).show();
            break;
        case CONTEXT_MENU_GROUP_RENAME:
            Toast.makeText(this, "这是group的重命名", Toast.LENGTH_SHORT).show();
            break;
        case CONTEXT_MENU_CHILD_EDIT:
            Toast.makeText(this, "这是child的编辑", Toast.LENGTH_SHORT).show();
            break;
        case CONTEXT_MENU_CHILD_DELETE:
            Toast.makeText(this, "这是child的删除", Toast.LENGTH_SHORT).show();
            break;

        default:
            break;
        }   

        return super.onContextItemSelected(item);
    }
}

在MainActivity.java中,我们给ExpandableListView添加了上下文菜单,长按group或者child的某一项都能弹出上下文菜单,另外,在group和child中,都添加了一个这里写图片描述这样的按钮,本来是打算,点击group中的此按钮弹出和长按group时弹出一样的上下文菜单,点击child上面的此按钮时也弹出相应的上下文菜单,但是此问题没能解决。就先放在这里了。

代码在这里:http://download.csdn.net/detail/hnyzwtf/9397117

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/148389.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • idea2021.10 激活码mac版本-激活码分享

    (idea2021.10 激活码mac版本)2021最新分享一个能用的的激活码出来,希望能帮到需要激活的朋友。目前这个是能用的,但是用的人多了之后也会失效,会不定时更新的,大家持续关注此网站~IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.html…

    2022年3月28日
    65
  • Arduino文档阅读笔记-RFID工作原理及RC522模块介绍

    RFID工作原理RFID(RadioFrequencyIdentification):无线射频识别RFID由2个部分组成:应答器/标签被贴在某个物体上的东东。无线接收器用于读取应答器/标签上的数据。读卡器由频射模块及高平磁场组成。Tag/应答器为待感应设备,此设备不包含电池。他只包含微型集成电路芯片及存储数据的介质以及接收和发送信号的天线。读取tag中的数据,首先要放…

    2022年4月8日
    85
  • 细说PyCharm的安装和配置[通俗易懂]

    细说PyCharm的安装和配置[通俗易懂]PyCharm的安装和设置PyCharm是一款非常好用的PythonIDE,由JetBrains开发和维护,(同时JetBrains还开发了另外一些知名IDE—-IntelliJIDEA和WebStorm)JetBrains官网:www.jetbrains.comPyCharm分为免费(Community,社区版)和收费的(Professional,专业版)通常情况下免费的版本就可以使用(学生党狂喜)PyCharm的安装包格式:pycharm-版本-日期安装步骤就是Next,选安装盘

    2022年8月29日
    1
  • idea激活码2019版激活方式实测可用

    今天来更新一下2019版本的idea激活方式。

    2022年3月14日
    67
  • 免费申请国外免费域名超详细教程[通俗易懂]

    免费申请国外免费域名超详细教程[通俗易懂]1.首先申请免费域名网站:https://my.freenom.com/domains.php2.填入域名,这里我们以xcflag为列(尽量选择复杂一点的或者五个字母以上的域名,因为简单的有些域名是需要收费的),点击检查可用性。3.可以看到很多免费的域名(用的谷歌翻译插件,翻译有时候不是很准确,free翻译过来应该是免费而不是自由,之后会写一些关于谷歌插件的笔记,详细讲解)4.我们选择xcflag.tk点击立即获取,稍等一会点击购物车查看绿色按钮5.默认三个月试用,这里下拉框我们选择十二个月

    2022年6月30日
    81
  • pxe装机「建议收藏」

    pxe装机「建议收藏」安装环境:一台已安装Linux系统的主机作为PXEServer,本文中PXEServer使用的系统是CentOS7;若干台待安装CentOS7的裸主机作为PXEClient;PXEServer与所有PXEClient处于同一局域网中;所有主机支持PXE启动安装方式。PXEServer安装及配置流程:\1.配置DHCP服务\2.配置TFTP服务\3.配…

    2022年6月16日
    29

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号