Android实现列表仿联系人快速查找和关键字搜索



列表按字母顺序排序,右侧实现根据首字母快速查找,输入框输入首字母或元素第一个字也可以实现快速查找。

Android实现列表仿联系人快速查找和关键字搜索_第1张图片

页面布局如下:

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

   android:layout_width="match_parent"

   android:layout_height="match_parent"

   android:orientation="vertical">

 

   

       android:id="@+id/et"

       android:layout_width="match_parent"

       android:layout_height="50dp"

       android:layout_margin="10dp"

       android:background="@drawable/arrow_down"

       android:hint="快速查找">

   com.example.demo.view.ClearEditText>

 

   <FrameLayout

       android:layout_width="fill_parent"

       android:layout_height="fill_parent">

 

       <ListView

           android:id="@+id/lv"

           android:layout_width="fill_parent"

           android:layout_height="fill_parent"

           android:layout_gravity="center"

           android:layout_marginLeft="10dp"

           android:layout_marginRight="20dp"

           android:divider="@null"

           android:scrollbars="none"/>

 

       <TextView

           android:id="@+id/tv"

           android:layout_width="80.0dip"

           android:layout_height="80.0dip"

           android:layout_gravity="center"

           android:background="@drawable/text_shape_bg2"

           android:gravity="center"

           android:textColor="#ffffffff"

           android:textSize="30.0dip"

           android:visibility="invisible"/>

 

       

           android:id="@+id/sidrbar"

           android:layout_width="30.0dip"

           android:layout_height="fill_parent"

           android:layout_gravity="right|center"/>

   FrameLayout>

LinearLayout>

 

在布局文件中,输入框ClearEditText和快速查找的SideBar需要自定义实现。

ClearEditText

publicclass ClearEditTextextends EditTextimplements OnFocusChangeListener,

      TextWatcher {

   /**

    *删除按钮的引用

    */

   private DrawablemClearDrawable;

 

   public ClearEditText(Context context) {

      this(context,null);

   }

 

   

   //这个构造方法也很重要,不加这个很多属性不能再XML里面定义

   public ClearEditText(Context context, AttributeSet attrs) {

      this(context, attrs, android.R.attr.editTextStyle);

   }

 

   public ClearEditText(Context context, AttributeSet attrs, int defStyle) {

      super(context, attrs, defStyle);

      init();

   }

 

   privatevoid init() {

      //获取EditText的删除文字图片,假如没有设置我们就使用默认的图片

      mClearDrawable = getCompoundDrawables()[2];

      if (mClearDrawable ==null) {

          mClearDrawable = getResources().getDrawable(

                 R.drawable.emotionstore_progresscancelbtn);

      }

      //图片被绘制的区域

      mClearDrawable.setBounds(0, 0,

             mClearDrawable.getIntrinsicWidth() / 3 * 2,

             mClearDrawable.getIntrinsicHeight() / 3 * 2);

      setClearIconVisible(false);

      setOnFocusChangeListener(this);

      addTextChangedListener(this);

   }

 

   /**

    *因为我们不能直接给EditText设置点击事件,所以我们用记住我们按下的位置来模拟点击事件当我们按下的位置横坐标在( EditText的宽-

    *图标到控件右边的间距-图标的宽)EditText的宽-图标到控件右边的间距)之间我们就算点击了图标,竖直方向没有考虑

    */

   @Override

   publicbooleanonTouchEvent(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("");

             }

          }

      }

 

      returnsuper.onTouchEvent(event);

   }

 

   /**

    *ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏

    */

   @Override

   publicvoid onFocusChange(View v,boolean hasFocus) {

      if (hasFocus) {

          setClearIconVisible(getText().length()> 0);

      }else {

          setClearIconVisible(false);

      }

   }

 

   /**

    *设置清除图标的显示与隐藏,调用setCompoundDrawablesEditText绘制上去

    *

    *@param visible

    */

   protectedvoid setClearIconVisible(boolean visible) {

      Drawable right = visible ?mClearDrawable :null;

      setCompoundDrawables(getCompoundDrawables()[0],

             getCompoundDrawables()[1], right, getCompoundDrawables()[3]);

   }

 

   /**

    *当输入框里面内容发生变化的时候回调的方法

    */

   @Override

   publicvoid onTextChanged(CharSequence s,int start,int count,int after) {

      setClearIconVisible(s.length()> 0);

   }

 

   @Override

   publicvoid beforeTextChanged(CharSequence s,int start,int count,

          int after) {

 

   }

 

   @Override

   publicvoid afterTextChanged(Editable s) {

 

   }

 

   /**

    *设置晃动动画控件晃动(根据需求)

    */

   publicvoid setShakeAnimation() {

      this.setAnimation(shakeAnimation(5));

   }

 

   /**

    *晃动动画

    *

    *@param counts

    *           1秒钟晃动多少次

    *@return

    */

   publicstatic Animation shakeAnimation(int counts) {

      AnimationtranslateAnimation =new TranslateAnimation(0, 10, 0, 0);

      translateAnimation.setInterpolator(new CycleInterpolator(counts));

      translateAnimation.setDuration(1000);

      return translateAnimation;

   }

 

SideBar

 

publicclass SideBarextends View {

   //触摸事件

   private OnTouchingLetterChangedListeneronTouchingLetterChangedListener;

   // 26个字符

   publicstatic String[]b = {"A","B","C","D","E","F","G","H","I",

          "J","K","L","M","N","O","P","Q","R","S","T","U","V",

          "W","X","Y","Z","#" };

   privateintchoose = -1;//选中

   private Paintpaint =new Paint();

 

   private TextViewmTextDialog;

 

   publicvoid setTextView(TextView mTextDialog) {

      this.mTextDialog = mTextDialog;

   }

 

 

   public SideBar(Context context, AttributeSet attrs,int defStyle) {

      super(context, attrs, defStyle);

   }

 

   public SideBar(Context context, AttributeSet attrs) {

      super(context, attrs);

   }

 

   public SideBar(Context context) {

      super(context);

   }

 

   /**

    *重写这个方法

    */

   protectedvoid onDraw(Canvas canvas) {

      super.onDraw(canvas);

      //获取焦点改变背景颜色.

      int height = getHeight();//获取对应高度

      int width = getWidth();//获取对应宽度

      int singleHeight = height /b.length;//获取每一个字母的高度

 

      for (int i = 0; i <b.length; i++) {

          paint.setColor(Color.rgb(33, 65, 98));

          // paint.setColor(Color.WHITE);

          paint.setTypeface(Typeface.DEFAULT_BOLD);

          paint.setAntiAlias(true);

          paint.setTextSize(20);

          //选中的状态

          if (i ==choose) {

             paint.setColor(Color.parseColor("#ff6600"));

             paint.setFakeBoldText(true);

          }

          // x坐标等于中间-字符串宽度的一半.

          float xPos = width / 2 -paint.measureText(b[i]) / 2;

          float yPos = singleHeight * i + singleHeight;

          canvas.drawText(b[i], xPos, yPos,paint);

          paint.reset();//重置画笔

      }

 

   }

 

   @Override

   publicboolean dispatchTouchEvent(MotionEvent event) {

      finalint action = event.getAction();

      finalfloat y = event.getY();//点击y坐标

      finalint oldChoose =choose;

      final OnTouchingLetterChangedListener listener = onTouchingLetterChangedListener;

      finalint c = (int) (y / getHeight() *b.length);//点击y坐标与sidbar总高度的比例*b数组的长度就等于点击b中的个数.

 

      switch (action) {

          case MotionEvent.ACTION_UP:

             setBackgroundDrawable(new ColorDrawable(0x00000000));

             choose = -1;//

             invalidate();

             if (mTextDialog !=null) {

                 mTextDialog.setVisibility(View.INVISIBLE);

             }

             break;

 

          default:

             setBackgroundResource(R.drawable.sidebar_background);

             if (oldChoose != c) {

                 if (c >= 0&& c <b.length) {

                    if (listener !=null) {

                        listener.onTouchingLetterChanged(b[c]);

                    }

                    if (mTextDialog !=null) {

                        mTextDialog.setText(b[c]);

                        mTextDialog.setVisibility(View.VISIBLE);

                    }

 

                    choose = c;

                    invalidate();

                 }

             }

 

             break;

      }

      returntrue;

   }

 

   /**

    *向外公开的方法

    *

    *@param onTouchingLetterChangedListener

    */

   publicvoid setOnTouchingLetterChangedListener(

          OnTouchingLetterChangedListener onTouchingLetterChangedListener) {

      this.onTouchingLetterChangedListener = onTouchingLetterChangedListener;

   }

 

   /**

    *接口

    *

    *@author coder

    *

    */

   publicinterface OnTouchingLetterChangedListener {

      publicvoid onTouchingLetterChanged(String s);

   }

 

}

实现列表按字母顺序展示需要用到汉字转拼音的工具类:

汉字转拼音类CharacterParser

publicclassCharacterParser {

   privatestaticint[]pyvalue =newint[] {-20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032,

          -20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728,

          -19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261,

          -19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961,

          -18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490,

          -18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, -17997, -17988,

          -17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692,

          -17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733,

          -16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419,

          -16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959,

          -15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631,

          -15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180,

          -15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941,

          -14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857,

          -14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353,

          -14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094,

          -14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831,

          -13658, -13611, -13601, -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329,

          -13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860,

          -12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300,

          -12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358,

          -11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014,

          -10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309,

          -10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254};

   publicstatic String[]pystr =new String[]    


{"a","ai","an","ang","ao","ba","bai","ban","bang","bao","bei","ben","beng","bi","bian",

 "biao","bie","bin","bing","bo","bu","ca","cai","can","cang","cao","ce","ceng","cha","

chai","chan","chang","chao","che", "chen","cheng","chi","chong","chou","chu","chuai",

"chuan","chuang","chui","chun","chuo","ci","cong","cou","cu","cuan","cui","cun","cuo",

"da","dai","dan","dang","dao","de","deng","di","dian","diao","die","ding","diu","dong",

"dou","du", "duan","dui","dun","duo","e","en","er","fa","fan","fang","fei","fen","feng",

"fo","fou","fu","ga","gai","gan","gang", "gao","ge","gei","gen","geng","gong","gou","gu",

"gua","guai","guan","guang","gui","gun","guo","ha","hai","han","hang", "hao","he","hei",

"hen","heng","hong","hou","hu","hua","huai","huan","huang","hui","hun","huo","ji","jia",

"jian", "jiang","jiao","jie","jin","jing","jiong","jiu","ju","juan","jue","jun","ka","kai",

"kan","kang","kao","ke","ken", "keng","kong","kou","ku","kua","kuai","kuan","kuang","kui",

"kun","kuo","la","lai","lan","lang","lao","le","lei","leng","li","lia","lian","liang","liao",

"lie","lin","ling","liu","long","lou","lu","lv","luan","lue","lun","luo","ma","mai" "man",

"mang","mao","me","mei","men","meng","mi","mian","miao","mie","min","ming","miu","mo","mou",

"mu","na","nai","nan","nang","nao","ne","nei","nen","neng","ni","nian","niang","niao","nie",

"nin","ning","niu","nong","nu","nv","nuan","nue","nuo","o","ou","pa","pai","pan","pang","pao",

"pei","pen","peng","pi","pian","piao","pie","pin","ping","po","pu", "qi","qia","qian","qiang",

"qiao","qie","qin","qing","qiong","qiu","qu","quan","que","qun","ran","rang","rao","re","ren",

"reng","ri","rong","rou","ru","ruan","rui","run","ruo","sa","sai","san","sang","sao","se","sen",

"seng","sha","shai","shan","shang","shao","she","shen","sheng","shi","shou","shu","shua","shuai",

"shuan","shuang","shui","shun","shuo","si","song","sou","su","suan","sui","sun","suo","ta","tai",

"tan","tang","tao","te","teng","ti","tian","tiao", "tie","ting","tong","tou","tu","tuan","tui",

"tun","tuo","wa","wai","wan","wang","wei","wen","weng","wo","wu","xi", "xia","xian","xiang",

"xiao","xie","xin","xing","xiong","xiu","xu","xuan","xue","xun","ya","yan","yang","yao","ye",

"yi" "yin","ying","yo","yong","you","yu","yuan","yue","yun","za","zai","zan","zang","zao",

"ze","zei","zen","zeng","zha", "zhai","zhan","zhang","zhao","zhe","zhen","zheng","zhi",

"zhong","zhou","zhu","zhua","zhuai","zhuan","zhuang","zhui","zhun","zhuo","zi","zong",

"zou","zu","zuan","zui","zun","zuo"};

   private StringBuilderbuffer;

   private Stringresource;

   privatestatic CharacterParsercharacterParser =new CharacterParser();

 

   publicstatic CharacterParser getInstance() {

      returncharacterParser;

   }

 

   public String getResource() {

      returnresource;

   }

 

   publicvoid setResource(String resource) {

      this.resource = resource;

   }

 

   /** *汉字转成ASCII* * @param chs *@return */

   privateint getChsAscii(String chs) {

      int asc = 0;

      try {

          byte[] bytes = chs.getBytes("gb2312");

          if (bytes ==null || bytes.length > 2 || bytes.length <= 0) {

             thrownew RuntimeException("illegal resource string");

          }

          if (bytes.length == 1) {

             asc = bytes[0];

          }

          if (bytes.length == 2) {

             int hightByte = 256 + bytes[0];

             int lowByte = 256 + bytes[1];

             asc = (256 * hightByte + lowByte) - 256 * 256;

          }

      }catch (Exception e) {

          System.out.println("ERROR:ChineseSpelling.class-getChsAscii(String chs)" + e);

      }

      return asc;

   }

 

   /** *单字解析 * *@param str *@return */

   public String convert(String str) {

      String result =null;

      int ascii = getChsAscii(str);

      if (ascii > 0 && ascii < 160) {

          result = String.valueOf((char) ascii);

      }else {

          for (int i = (pyvalue.length - 1); i >= 0; i--) {

             if (pyvalue[i] <= ascii) {

                 result =pystr[i];

                 break;

             }

          }

      }

      return result;

   }

 

   /** *词组解析 * *@param chs *@return */

   public String getSelling(String chs) {

      String key, value;

      buffer =new StringBuilder();

      for (int i = 0; i < chs.length(); i++) {

          key = chs.substring(i, i + 1);

          if (key.getBytes().length >= 2) {

             value = (String) convert(key);

             if (value ==null) {

                 value ="unknown";

             }

          }else {

             value = key;

          }

          buffer.append(value);

      }

      returnbuffer.toString();

   }

 

   public String getSpelling() {

      returnthis.getSelling(this.getResource());

   }

 

}

 

MainActivity中实现获取集合数据并使用:

        //声明变量

   private SideBarsideBar;

   private TextViewtv;

   private ListViewlv;

   private MyAdapteradapter;

   private ClearEditTextet;

   private ListmSortList;

   privateCharacterParsercharacterParser;

   @Override

   protectedvoid onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_main);

 

      sideBar = (SideBar) findViewById(R.id.sidrbar);

      tv = (TextView) findViewById(R.id.tv);

      sideBar.setTextView(tv);

      lv = (ListView) findViewById(R.id.lv);

      et = (ClearEditText) findViewById(R.id.et);

 

      //汉字转拼音的工具类初始化

      characterParser = CharacterParser.getInstance();

      //该集合根据实际,从网络获取数据

      mSortList = DB.getBean();

      

      //便利集合,根据每个元素的name字段转为拼音的首字母设置元素的分组head

      for (int i = 0; i < mSortList.size(); i++) {

          LinkManBean sortModel =mSortList.get(i);

          //汉字转拼音的方法

         String pinyin =getPingYin(sortModel.name.trim());

          String sortString = pinyin.substring(0, 1).toUpperCase();

          if (sortString.matches("[A-Z]")) {

             sortModel.head = sortString.toUpperCase();

          }else {

             sortModel.head ="#";

          }

      }

      //集合排序方法

      Collections.sort(mSortList);

      //刷新数据

      adapter =newMyAdapter(this, mSortList);

      lv.setAdapter(adapter);

      // sideBar设置触摸监听

      sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

          @Override

          publicvoid onTouchingLetterChanged(String s) {

      //根据分类列的索引号获得该序列的首个位置

      int position =adapter.getPositionForSection(s.charAt(0));

             if (position != -1) {

                 //列表显示到此位置

                 lv.setSelection(position);

             }

          }

      });

      

      // edittext添加文本改变监听

      et.addTextChangedListener(new TextWatcher() {

          @Override

      publicvoid onTextChanged(CharSequence s,int start,int before,

                 int count) {

 

             filterData(s.toString());

          }

 

          @Override

      publicvoid beforeTextChanged(CharSequence s,int start,int count,

                 int after) {

          }

 

          @Override

      publicvoid afterTextChanged(Editable s) {

          }

      });

 

      lv.setOnItemClickListener(new OnItemClickListener() {

          @Override

      publicvoid onItemClick(AdapterView parent, View view,

                 int position,long id) {

             Toast.makeText(MainActivity.this,adapter.getList().get(position).name,

                    Toast.LENGTH_LONG).show();

          }

      });

   }

 

 

   /**

    *将字符串中的中文转化为拼音,其他字符不变

    */

   public StringgetPingYin(String inputString) {

      HanyuPinyinOutputFormat format =new HanyuPinyinOutputFormat();

      format.setCaseType(HanyuPinyinCaseType.LOWERCASE);

      format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

      format.setVCharType(HanyuPinyinVCharType.WITH_V);

 

      Pattern p = Pattern.compile("^[\u4E00-\u9FA5A-Za-z_]+$");

      Matcher matcher = p.matcher(inputString.substring(0, 1));

      if (matcher.find()) {

          char[] input = inputString.trim().toCharArray();

          String output ="";

          try {

             for (int i = 0; i < input.length; i++) {

                 if (java.lang.Character.toString(input[i]).matches(

                        "[\\u4E00-\\u9FA5]+")) {

                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(

                           input[i], format);

                    output += temp[0];

                 }else

                    output += java.lang.Character.toString(input[i]);

             }

          }catch (BadHanyuPinyinOutputFormatCombination e) {

             e.printStackTrace();

          }

          return output;

      }else {

          return"unknown";

      }

   }

 

   /**

    *将字符串中的中文转化为拼音,其他字符不变

    */

privatevoidfilterData(String filterStr) {

      List filterDateList =new ArrayList();

      //filterStr为空则集合为最初获取的数据不做改变

      if (TextUtils.isEmpty(filterStr)) {

          filterDateList =mSortList;

      }else {

      //filterStr不为空,便利最初获取的集合数据,将集合中字段首字母与filterStr相同的放入新的集合并排序。刷新数据展示

          filterDateList.clear();

          for (LinkManBean sortModel :mSortList) {

             String name = sortModel.name;

             if (name.toUpperCase().indexOf(

          filterStr.toString().toUpperCase()) != -1||                     characterParser.getSelling(name).toUpperCase()                          .startsWith(filterStr.toString().toUpperCase())) {

                 filterDateList.add(sortModel);

             }

          }

      }

 

      //根据a-z进行排序

      Collections.sort(filterDateList);

      adapter.updateListView(filterDateList);

   }

MyAdapter类:

classMyAdapterextends BaseAdapter {

      private Contextcontext;

      private Listbeans;

 

      publicMyAdapter(Context context, List beans) {

          super();

          this.context = context;

          this.beans = beans;

      }

      

      public List getList() {

 

          returnbeans;

      }

 

      publicvoid updateListView(List beans) {

          this.beans = beans;

          notifyDataSetChanged();

      }

 

      @Override

      publicint getCount() {

          returnbeans.size();

      }

 

      class ViewHolder {

          LinearLayoutlytitle;

          RelativeLayoutlycontent;

          TextViewtvLetter;

          TextViewtvTitle;

      }

 

      @Override

      public View getView(int position, View convertView, ViewGroup parent) {

          ViewHolder viewHolder =null;

          LinkManBean mContent =beans.get(position);

          if (convertView ==null) {

             viewHolder =new ViewHolder();

             convertView = LayoutInflater.from(context).inflate(

                    R.layout.item,null);

             viewHolder.tvTitle = (TextView) convertView

                    .findViewById(R.id.title);

             viewHolder.tvLetter = (TextView) convertView

                    .findViewById(R.id.catalog);

             viewHolder.lytitle = (LinearLayout) convertView

                    .findViewById(R.id.lytitle);

             viewHolder.lycontent = (RelativeLayout) convertView

                    .findViewById(R.id.lycontent);

             convertView.setTag(viewHolder);

          }else {

             viewHolder = (ViewHolder) convertView.getTag();

          }

          //通过该项的位置,获得所在分类组的索引号

          int section =getSectionForPosition(position);

 

      //根据是否为某组第一个元素控制组名的显示

      //与否根据分组的序列号得到改组的首个元素 

      if (position ==getPositionForSection(section))

          {

             viewHolder.lytitle.setVisibility(View.VISIBLE);

             viewHolder.tvLetter.setText(mContent.head);

          }else {

             viewHolder.lytitle.setVisibility(View.GONE);

          }

          String name =beans.get(position).name;

          viewHolder.tvTitle.setText(name);

          return convertView;

      }

 

      publicintgetSectionForPosition(int position) {

          returnbeans.get(position).head.charAt(0);

      }

 

      publicintgetPositionForSection(int section) {//65

          for (int i = 0; i < getCount(); i++) {

             String sortStr =beans.get(i).head;

             char firstChar = sortStr.toUpperCase().charAt(0);

             if (firstChar == section) {

                 return i;

             }

          }

          return -1;

      }

 

      @Override

      public Object getItem(int position) {

          returnnull;

      }

 

      @Override

      publiclong getItemId(int position) {

          return 0;

      }

   }

item布局:

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"

   android:layout_width="fill_parent"

   android:layout_height="wrap_content"

   android:gravity="center_vertical"

   android:orientation="vertical">

 

   <LinearLayout

       android:id="@+id/lytitle"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:orientation="vertical">

 

       <TextView

           android:id="@+id/catalog"

           android:layout_width="fill_parent"

           android:layout_height="wrap_content"

           android:paddingLeft="10dip"

           android:text="A"

           android:textColor="#3660b6"

           android:textSize="18sp"

           android:textStyle="bold"/>

 

       <TextView

           android:layout_width="fill_parent"

           android:layout_height="1dp"

           android:background="#3660b6"/>

   LinearLayout>

 

   <RelativeLayout

       android:id="@+id/lycontent"

       android:layout_width="fill_parent"

       android:layout_height="fill_parent"

       android:layout_below="@+id/lytitle">

 

       <LinearLayout

           android:layout_width="fill_parent"

           android:layout_height="fill_parent"

           android:gravity="center_vertical|left">

 

           <TextView

               android:id="@+id/title"

               android:layout_width="wrap_content"

               android:layout_height="fill_parent"

               android:layout_gravity="center_vertical"

               android:layout_marginLeft="13dp"

               android:layout_weight="1.0"

               android:gravity="center_vertical"

               android:paddingBottom="15dp"

               android:paddingTop="15dp"

               android:text="hhhh"

               android:textColor="#222222"

               android:textSize="16sp"/>

       LinearLayout>

   RelativeLayout>

 

RelativeLayout>

你可能感兴趣的:(Android实现列表仿联系人快速查找和关键字搜索)