项目开发中ExpandableListView的功能非常强大,能简单的实现很多ListView实现起来很复杂的工作,监听事件的方法如下图:
但是也有一个缺点,就是ExpandableListView实现Group条目下的child子条目的长按点击事件操作算是十分不容易,因为ExpandableListView的点击事件是Group和Child共享一个长按点击接监听方法;所以有时为了拿到Child子条目的数据,必须要拿到Group条目对应的groupPosition。但是ExpandableListView实现长按监听的参数只有一个position位置信息,显得是尬;ExpandableListView的长按监听方法如下:
<span style="font-size:14px;"> @Override
protected void initListenner() {
mConversationLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
return false;
}
});
}</span>
所以,为了解决上诉问题。我想到了一种简单的方法,那就是LisetView和ViewHolder那样实现打标记的方法setTag()和getTag()从而拿到对方的信息;
注意:这里对应的R.id.iv_touxiang和R.id.iv_online必须是资源空间ID,道理如同LisetView和ViewHolder相互捆绑一样。这样应该很容易理解吧。
GroupView代码如下:
<span style="font-size:14px;"> @Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(mActivity, R.layout.list_contact_group, null);
}
ImageView iv_indicator = (ImageView) convertView.findViewById(R.id.iv_indicator);
TextView tv_group = (TextView) convertView.findViewById(R.id.tv_group);
TextView tv_count = (TextView) convertView.findViewById(R.id.tv_count);
iv_indicator.setSelected(isExpanded);
tv_group.setText(getRosterGroup(groupPosition).getName());
tv_count.setText(getRosterEntries(groupPosition).size() + "");
//通过打标记的方法来获取groupPosition和childPosition
convertView.setTag(R.id.iv_touxiang, groupPosition);
convertView.setTag(R.id.iv_online, -1);
return convertView;
}</span>
ChildView代码如下:
<span style="font-size:14px;"> @Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(mActivity, R.layout.list_contact_child, null);
}
TextView tv_name = (TextView) convertView.findViewById(R.id.tv_name);
RosterEntry rosterEntry = getRosterEntries(groupPosition).get(childPosition);
tv_name.setText(rosterEntry.getName() + "====" + rosterEntry.getUser());
//通过打标记的方法来获取groupPosition和childPosition
convertView.setTag(R.id.iv_touxiang, groupPosition);
convertView.setTag(R.id.iv_online, childPosition);
return convertView;
}</span>
最后,当我们长按子条目师,触发长按事件,我们就可以通过getTag()方法拿到当前条目的groupPosition和childPosition了
代码如下:
<span style="font-size:14px;"> @Override
protected void initListenner() {
mConversationLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int groupPosition = (Integer) view.getTag(R.id.iv_touxiang);
int childPosition = (Integer) view.getTag(R.id.iv_online);
LogUtils.d("groupPosition=" + groupPosition + "===========childPosition=" + childPosition);
return false;
}
});
}</span>
下面附输出日志
03-23 03:12:50.990 15853-15853/? D/LogUtils: groupPosition=0===========childPosition=1