首页 > 代码库 > Android 利用ExpandableListView显示和查询仿QQ分组列表用户信息
Android 利用ExpandableListView显示和查询仿QQ分组列表用户信息
在我们的项目开发过程中,经常会对用户的信息进行分组,即通过组来显示用户的信息,同时通过一定的查询条件来显示查询后的相关用户信息,并且通过颜色选择器来设置列表信息的背景颜色。
其中借鉴xiaanming:http://blog.csdn.net/xiaanming/article/details/12684155
下面来看看项目运行后的效果图以及代码结构图:
下面通过代码来实现整个效果。
1.主界面布局activity_main.xml
<span style="font-size:18px;"><LinearLayout 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" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" > <Button android:id="@+id/my_btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="生成部门列表" /> <com.example.myexpandabledemo.ClearEditText android:id="@+id/filter_edit" android:layout_width="fill_parent" android:layout_height="60dp" android:layout_marginTop="10dip" android:background="@drawable/search_bar_edit_selector" android:drawableLeft="@drawable/search_bar_icon_normal" android:hint="搜索" android:singleLine="true" android:textSize="15.0dip" /> <TextView android:id="@+id/no_search_result_tv" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="未搜索到结果" android:visibility="gone" /> <ExpandableListView android:id="@+id/my_expand_lv" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout></span>分析:主界面主要有一个Button,一个自定义搜索的ClearEditText,一个无查询结果的TextView,一个列表信息显示ExpandableListView。其中Button主要用来生成列表信息。
2.自定义的ClearEditText的搜索框CliearEditText.java
<span style="font-size:18px;">package com.example.myexpandabledemo; import android.content.Context; import android.graphics.drawable.Drawable; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.animation.Animation; import android.view.animation.CycleInterpolator; import android.view.animation.TranslateAnimation; import android.widget.EditText; public class ClearEditText extends EditText implements OnFocusChangeListener, TextWatcher { /** * 删除按钮的引用 */ private Drawable mClearDrawable; public ClearEditText(Context context) { this(context, null); } public ClearEditText(Context context, AttributeSet attrs) { //这里构造方法也很重要,不加这个很多属性不能再XML里面定义 this(context, attrs, android.R.attr.editTextStyle); } public ClearEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { //获取EditText的DrawableRight,假如没有设置我们就使用默认的图片 mClearDrawable = getCompoundDrawables()[2]; if (mClearDrawable == null) { mClearDrawable = getResources() .getDrawable(R.drawable.emotionstore_progresscancelbtn); } mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); setClearIconVisible(false); setOnFocusChangeListener(this); addTextChangedListener(this); } /** * 因为我们不能直接给EditText设置点击事件,所以我们用记住我们按下的位置来模拟点击事件 * 当我们按下的位置 在 EditText的宽度 - 图标到控件右边的间距 - 图标的宽度 和 * EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标,竖直方向没有考虑 */ @Override public boolean onTouchEvent(MotionEvent event) { if (getCompoundDrawables()[2] != null) { if (event.getAction() == MotionEvent.ACTION_UP) { boolean touchable = event.getX() > (getWidth() - getPaddingRight() - mClearDrawable.getIntrinsicWidth()) && (event.getX() < ((getWidth() - getPaddingRight()))); if (touchable) { this.setText(""); } } } return super.onTouchEvent(event); } /** * 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏 */ @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { setClearIconVisible(getText().length() > 0); } else { setClearIconVisible(false); } } /** * 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去 * @param visible */ protected void setClearIconVisible(boolean visible) { Drawable right = visible ? mClearDrawable : null; setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]); } /** * 当输入框里面内容发生变化的时候回调的方法 */ @Override public void onTextChanged(CharSequence s, int start, int count, int after) { setClearIconVisible(s.length() > 0); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } /** * 设置晃动动画 */ public void setShakeAnimation(){ this.setAnimation(shakeAnimation(5)); } /** * 晃动动画 * @param counts 1秒钟晃动多少下 * @return */ public static Animation shakeAnimation(int counts){ Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0); translateAnimation.setInterpolator(new CycleInterpolator(counts)); translateAnimation.setDuration(1000); return translateAnimation; } }</span>
搜索框颜色选择器:
<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:drawable="@drawable/search_bar_edit_pressed"></item> <item android:state_pressed="true" android:drawable="@drawable/search_bar_edit_pressed"></item> <item android:drawable="@drawable/search_bar_edit_normal"></item> </selector></span>
3.汉字拼音排序所需要的汉字转拼音:CharacterParser.java
<span style="font-size:18px;">package com.example.myexpandabledemo; /** * Java汉字转换为拼音 * */ public class CharacterParser { private static int[] pyvalue = http://www.mamicode.com/new int[] {-20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032,>4. 拼音比较类:PinyinComparator.java<span style="font-size:18px;">package com.example.myexpandabledemo; import java.util.Comparator; public class PinyinComparator implements Comparator<GroupMemberBean> { public int compare(GroupMemberBean o1, GroupMemberBean o2) { if (o1.getSortLetters().equals("@") || o2.getSortLetters().equals("#")) { return -1; } else if (o1.getSortLetters().equals("#") || o2.getSortLetters().equals("@")) { return 1; } else { return o1.getSortLetters().compareTo(o2.getSortLetters()); } } } </span>5. 显示列表信息的名字以及其拼音首字母 GrouMemberBean.java<span style="font-size:18px;">package com.example.myexpandabledemo; public class GroupMemberBean { private String name; //显示的数据 private String sortLetters; //显示数据拼音的首字母 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSortLetters() { return sortLetters; } public void setSortLetters(String sortLetters) { this.sortLetters = sortLetters; } } </span>6.ExpandaleListView 适配器MyExpandableAdapter.java<span style="font-size:18px;">package com.example.myexpandabledemo; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MyExpandableAdapter extends BaseExpandableListAdapter { private Context mContext; private List<GroupMemberBean> mGroup; private List<List<GroupMemberBean>> mChild; private LayoutInflater mInflater; public MyExpandableAdapter(Context mContext,List<GroupMemberBean> mGroup,List<List<GroupMemberBean>> mChild){ this.mContext = mContext; this.mGroup = mGroup; this.mChild = mChild; this.mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } /** * 当ListView数据发生变化时,调用此方法来更新ListView * * @param list */ public void updateListView(List<GroupMemberBean> mGroup,List<List<GroupMemberBean>> mChild) { this.mGroup = mGroup; this.mChild = mChild; notifyDataSetChanged(); } @Override public int getGroupCount() { // TODO Auto-generated method stub return mGroup.size(); } @Override public int getChildrenCount(int groupPosition) { // TODO Auto-generated method stub return mChild.get(groupPosition).size(); } @Override public Object getGroup(int groupPosition) { // TODO Auto-generated method stub return mGroup.get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { // TODO Auto-generated method stub return mChild.get(groupPosition).get(childPosition); } @Override public long getGroupId(int groupPosition) { // TODO Auto-generated method stub return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { // TODO Auto-generated method stub return childPosition; } @Override public boolean hasStableIds() { // TODO Auto-generated method stub return false; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { // TODO Auto-generated method stub GroupHolderView groupHolderView; if(convertView == null){ groupHolderView = new GroupHolderView(); convertView = (View) mInflater.inflate(R.layout.activity_group, null); groupHolderView.groupTv = (TextView) convertView.findViewById(R.id.my_group_tv); convertView.setTag(groupHolderView); }else{ groupHolderView = (GroupHolderView) convertView.getTag(); } groupHolderView.groupTv.setText(mGroup.get(groupPosition).getName()); return convertView; } @Override public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ChildHolderView childHolderView; if(convertView == null){ childHolderView = new ChildHolderView(); convertView = (View) mInflater.inflate(R.layout.activity_child, null); childHolderView.childIv = (ImageView) convertView.findViewById(R.id.my_child_iv); childHolderView.childTv = (TextView) convertView.findViewById(R.id.my_child_tv); childHolderView.childLl = (LinearLayout) convertView.findViewById(R.id.my_child_ll); convertView.setTag(childHolderView); }else{ childHolderView = (ChildHolderView) convertView.getTag(); } childHolderView.childTv.setText(mChild.get(groupPosition).get(childPosition).getName()); childHolderView.childLl.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(mContext, "group:" + mGroup.get(groupPosition).getName() + "->child:" + mChild.get(groupPosition).get(childPosition).getName(), Toast.LENGTH_SHORT).show(); } }); return convertView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { // TODO Auto-generated method stub return false; } class GroupHolderView{ TextView groupTv; } class ChildHolderView{ ImageView childIv; TextView childTv; LinearLayout childLl; } }</span>分析:
GroupHolderView:用于显示组信息
ChildHolderView:用于显示组下成员信息。包括一个LinearLayout,一个ImageView,一个TextVIew
private List<GroupMemberBean> mGroup; 包含组的所有List信息
private List<List<GroupMemberBean>> mChild;包含所有的组下成员信息<span style="font-size:18px;"> public void updateListView(List<GroupMemberBean> mGroup,List<List<GroupMemberBean>> mChild) { this.mGroup = mGroup; this.mChild = mChild; notifyDataSetChanged(); }</span>根据传入的mGroup,mChild来更新列表信息。7.GroupHolderView类所对应的activity_group.xml
<span style="font-size:18px;"><?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/my_group_tv" android:layout_width="wrap_content" android:layout_height="50dp" android:paddingLeft="50dp" android:gravity="center_vertical" /> </LinearLayout></span>
8.ChildHolderView类所对应的activity_child.xml<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/my_child_ll" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/my_child_selector" android:orientation="horizontal" > <ImageView android:id="@+id/my_child_iv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/ic_launcher" /> <TextView android:id="@+id/my_child_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout></span>分析:根据android:background="@drawable/my_child_selector" 颜色选择器来设置每个列表行(选中或正常)的背景色。9.颜色选择器my_child_selector.xml
<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:drawable="@color/press_color"></item> <item android:state_pressed="true" android:drawable="@color/press_color"></item> <item android:drawable="@color/normal_color"></item> </selector></span>
10.主界面实现代码:MainActivity.java<span style="font-size:18px;">package com.example.myexpandabledemo; import java.util.ArrayList; import java.util.Collections; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ExpandableListView; import android.widget.TextView; public class MainActivity extends Activity { private Button myBtn; private ExpandableListView myExpandLv; private ClearEditText myClearEt; private TextView noSearchResultTv; private MyExpandableAdapter myAdapter; private List<GroupMemberBean> groupBeanList; private List<List<GroupMemberBean>> childBeanList = new ArrayList<List<GroupMemberBean>>(); /** * 汉字转换成拼音的类 */ private CharacterParser characterParser; /** * 根据拼音来排列ListView里面的数据类 */ private PinyinComparator pinyinComparator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { noSearchResultTv = (TextView)this.findViewById(R.id.no_search_result_tv); myExpandLv = (ExpandableListView) this.findViewById(R.id.my_expand_lv); // 实例化汉字转拼音类 characterParser = CharacterParser.getInstance(); pinyinComparator = new PinyinComparator(); groupBeanList = filledData(this.getResources().getStringArray( R.array.depart)); List<GroupMemberBean> tempOne = filledData(this.getResources() .getStringArray(R.array.child_one)); List<GroupMemberBean> tempTwo = filledData(this.getResources() .getStringArray(R.array.child_two)); // 根据a-z进行排序源数据 Collections.sort(groupBeanList, pinyinComparator); Collections.sort(tempOne, pinyinComparator); Collections.sort(tempTwo, pinyinComparator); for (int i = 0; i < groupBeanList.size(); i++) { if (i % 2 == 0) { childBeanList.add(tempOne); } else { childBeanList.add(tempTwo); } } //用于生成列表信息 myBtn = (Button) this.findViewById(R.id.my_btn); myBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub myAdapter = new MyExpandableAdapter(MainActivity.this, groupBeanList, childBeanList); myExpandLv.setAdapter(myAdapter); myExpandLv.expandGroup(0); } }); myClearEt = (ClearEditText) this.findViewById(R.id.filter_edit); myClearEt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub filterData(s.toString()); } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * 为ListView填充数据 * * @param date * @return */ private List<GroupMemberBean> filledData(String[] date) { List<GroupMemberBean> mSortList = new ArrayList<GroupMemberBean>(); for (int i = 0; i < date.length; i++) { GroupMemberBean sortModel = new GroupMemberBean(); sortModel.setName(date[i]); // 汉字转换成拼音 String pinyin = characterParser.getSelling(date[i]); String sortString = pinyin.substring(0, 1).toUpperCase(); // 正则表达式,判断首字母是否是英文字母 if (sortString.matches("[A-Z]")) { sortModel.setSortLetters(sortString.toUpperCase()); } else { sortModel.setSortLetters("#"); } mSortList.add(sortModel); } return mSortList; } /** * 根据输入框中的值来过滤数据并更新ListView * * @param filterStr */ private void filterData(String filterStr) { List<GroupMemberBean> groupFilterList = new ArrayList<GroupMemberBean>(); List<GroupMemberBean> tempFilterList; List<List<GroupMemberBean>> childFilterList = new ArrayList<List<GroupMemberBean>>(); if (TextUtils.isEmpty(filterStr)) { groupFilterList = groupBeanList; childFilterList = childBeanList; noSearchResultTv.setVisibility(View.GONE); } else { groupFilterList.clear(); childFilterList.clear(); for (int i = 0; i < groupBeanList.size(); i++) { //标记departGroup是否加入元素 boolean isAddGroup = false; tempFilterList = new ArrayList<GroupMemberBean>(); GroupMemberBean sortModel = groupBeanList.get(i); String name = sortModel.getName(); // depart有字符直接加入 if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith( filterStr.toString())) { if (!groupFilterList.contains(sortModel)) { groupFilterList.add(sortModel); isAddGroup = true; } } for (int j = 0; j < childBeanList.get(i).size(); j++) { GroupMemberBean sortChildModel = childBeanList.get(i) .get(j); String childName = sortChildModel.getName(); // child有字符直接加入,其父也加入 if (childName.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(childName) .startsWith(filterStr.toString())) { tempFilterList.add(sortChildModel); if (!groupFilterList.contains(groupBeanList.get(i))) { groupFilterList.add(groupBeanList.get(i)); isAddGroup = true; } } } Collections.sort(tempFilterList, pinyinComparator); if (isAddGroup) { childFilterList.add(tempFilterList); } } // 根据a-z进行排序 Collections.sort(groupBeanList, pinyinComparator); } if (myAdapter != null) { myAdapter.updateListView(groupFilterList, childFilterList); if (TextUtils.isEmpty(filterStr)) { for (int i = 0; i < groupFilterList.size(); i++) { if (i == 0) { myExpandLv.expandGroup(i); continue; } myExpandLv.collapseGroup(i); } } else { //搜索的结果全部展开 for (int i = 0; i < groupFilterList.size(); i++) { myExpandLv.expandGroup(i); } } } //如果查询的结果为0时,显示为搜索到结果的提示 if(groupFilterList.size() == 0){ noSearchResultTv.setVisibility(View.VISIBLE); }else{ noSearchResultTv.setVisibility(View.GONE); } } } </span>
分析:<span style="font-size:18px;"> myBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub myAdapter = new MyExpandableAdapter(MainActivity.this, groupBeanList, childBeanList); myExpandLv.setAdapter(myAdapter); myExpandLv.expandGroup(0); } });</span>用于生成列表信息<span style="font-size:18px;">private List<GroupMemberBean> filledData(String[] date) </span>根据 res->array定义的字符数组,转化为List<GroupMemberBean><span style="font-size:18px;">private void filterData(String filterStr) {</span>根据查询条件更新列表信息,
重点:1.如果查询的条件为空,直接更新列表初始状态;假如:filterStr = “g”;
2.如果查询的结果为空,直接给出“未搜索到结果”提示;
3.如果Group中包含filterStr,GroupMemberBean sortModel 直接加入groupFilterList,并标记已加入isAddGroup = true;
如果Child中包含filterStr,定义临时的tempFilterList,GroupMemberBean sortChildModel加入到childFilterList,如果groupFilterList不包含其父组,并将其父加入到groupFilterList,并标记已加入isAddGroup=true;
最后如果isAddGroup=true,将tempFilterList加入到childFilterList。
4.通过myAdapter.updateListView(groupFilterList, childFilterList),更新列表信息。
其上为本博文的所有内容。
源代码下载:
http://download.csdn.net/detail/a123demi/7623975