Android之联系人PinnedHeaderListView使用

Android联系人中联系人列表页的ListView做得用户体验非常好的,于是想把它从源码中提取出来,以便日后使用。写了一个简单的例子,一方面算是给自己备忘,另一方面跟大家分享一下。

好了,先来看看效果图:



向上挤压的动画




选择右边的导航栏




好了,废话不多说,直接上代码


右侧导航栏 BladeView.java

[java]  view plain copy
  1. package com.example.pinnedheaderlistviewdemo.view;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.Canvas;  
  5. import android.graphics.Color;  
  6. import android.graphics.Paint;  
  7. import android.os.Handler;  
  8. import android.util.AttributeSet;  
  9. import android.view.Gravity;  
  10. import android.view.MotionEvent;  
  11. import android.view.View;  
  12. import android.widget.PopupWindow;  
  13. import android.widget.TextView;  
  14.   
  15. import com.example.pinnedheaderlistviewdemo.R;  
  16.   
  17. public class BladeView extends View {  
  18.     private OnItemClickListener mOnItemClickListener;  
  19.     String[] b = { "#""A""B""C""D""E""F""G""H""I""J""K",  
  20.             "L""M""N""O""P""Q""R""S""T""U""V""W""X",  
  21.             "Y""Z" };  
  22.     int choose = -1;  
  23.     Paint paint = new Paint();  
  24.     boolean showBkg = false;  
  25.     private PopupWindow mPopupWindow;  
  26.     private TextView mPopupText;  
  27.     private Handler handler = new Handler();  
  28.   
  29.     public BladeView(Context context, AttributeSet attrs, int defStyle) {  
  30.         super(context, attrs, defStyle);  
  31.     }  
  32.   
  33.     public BladeView(Context context, AttributeSet attrs) {  
  34.         super(context, attrs);  
  35.     }  
  36.   
  37.     public BladeView(Context context) {  
  38.         super(context);  
  39.     }  
  40.   
  41.     @Override  
  42.     protected void onDraw(Canvas canvas) {  
  43.         super.onDraw(canvas);  
  44.         if (showBkg) {  
  45.             canvas.drawColor(Color.parseColor("#AAAAAA"));  
  46.         }  
  47.   
  48.         int height = getHeight();  
  49.         int width = getWidth();  
  50.         int singleHeight = height / b.length;  
  51.         for (int i = 0; i < b.length; i++) {  
  52.             paint.setColor(Color.parseColor("#ff2f2f2f"));  
  53. //          paint.setTypeface(Typeface.DEFAULT_BOLD);   //加粗  
  54.             paint.setTextSize(getResources().getDimensionPixelSize(R.dimen.bladeview_fontsize));//设置字体的大小  
  55.             paint.setFakeBoldText(true);  
  56.             paint.setAntiAlias(true);  
  57.             if (i == choose) {  
  58.                 paint.setColor(Color.parseColor("#3399ff"));  
  59.             }  
  60.             float xPos = width / 2 - paint.measureText(b[i]) / 2;  
  61.             float yPos = singleHeight * i + singleHeight;  
  62.             canvas.drawText(b[i], xPos, yPos, paint);  
  63.             paint.reset();  
  64.         }  
  65.   
  66.     }  
  67.   
  68.     @Override  
  69.     public boolean dispatchTouchEvent(MotionEvent event) {  
  70.         final int action = event.getAction();  
  71.         final float y = event.getY();  
  72.         final int oldChoose = choose;  
  73.         final int c = (int) (y / getHeight() * b.length);  
  74.   
  75.         switch (action) {  
  76.         case MotionEvent.ACTION_DOWN:  
  77.             showBkg = true;  
  78.             if (oldChoose != c) {  
  79.                 if (c >= 0 && c < b.length) { //让第一个字母响应点击事件  
  80.                     performItemClicked(c);  
  81.                     choose = c;  
  82.                     invalidate();  
  83.                 }  
  84.             }  
  85.   
  86.             break;  
  87.         case MotionEvent.ACTION_MOVE:  
  88.             if (oldChoose != c) {  
  89.                 if (c >= 0 && c < b.length) { //让第一个字母响应点击事件  
  90.                     performItemClicked(c);  
  91.                     choose = c;  
  92.                     invalidate();  
  93.                 }  
  94.             }  
  95.             break;  
  96.         case MotionEvent.ACTION_UP:  
  97.             showBkg = false;  
  98.             choose = -1;  
  99.             dismissPopup();  
  100.             invalidate();  
  101.             break;  
  102.         }  
  103.         return true;  
  104.     }  
  105.   
  106.     private void showPopup(int item) {  
  107.         if (mPopupWindow == null) {  
  108.               
  109.             handler.removeCallbacks(dismissRunnable);  
  110.             mPopupText = new TextView(getContext());  
  111.             mPopupText.setBackgroundColor(Color.GRAY);  
  112.             mPopupText.setTextColor(Color.WHITE);  
  113.             mPopupText.setTextSize(getResources().getDimensionPixelSize(R.dimen.bladeview_popup_fontsize));  
  114.             mPopupText.setGravity(Gravity.CENTER_HORIZONTAL  
  115.                     | Gravity.CENTER_VERTICAL);  
  116.               
  117.             int height = getResources().getDimensionPixelSize(R.dimen.bladeview_popup_height);  
  118.               
  119.             mPopupWindow = new PopupWindow(mPopupText, height, height);  
  120.         }  
  121.   
  122.         String text = "";  
  123.         if (item == 0) {  
  124.             text = "#";  
  125.         } else {  
  126.             text = Character.toString((char) ('A' + item - 1));  
  127.         }  
  128.         mPopupText.setText(text);  
  129.         if (mPopupWindow.isShowing()) {  
  130.             mPopupWindow.update();  
  131.         } else {  
  132.             mPopupWindow.showAtLocation(getRootView(),  
  133.                     Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 00);  
  134.         }  
  135.     }  
  136.   
  137.     private void dismissPopup() {  
  138.         handler.postDelayed(dismissRunnable, 1500);  
  139.     }  
  140.   
  141.     Runnable dismissRunnable = new Runnable() {  
  142.   
  143.         @Override  
  144.         public void run() {  
  145.             // TODO Auto-generated method stub  
  146.             if (mPopupWindow != null) {  
  147.                 mPopupWindow.dismiss();  
  148.             }  
  149.         }  
  150.     };  
  151.   
  152.     public boolean onTouchEvent(MotionEvent event) {  
  153.         return super.onTouchEvent(event);  
  154.     }  
  155.   
  156.     public void setOnItemClickListener(OnItemClickListener listener) {  
  157.         mOnItemClickListener = listener;  
  158.     }  
  159.   
  160.     private void performItemClicked(int item) {  
  161.         if (mOnItemClickListener != null) {  
  162.             mOnItemClickListener.onItemClick(b[item]);  
  163.             showPopup(item);  
  164.         }  
  165.     }  
  166.   
  167.     public interface OnItemClickListener {  
  168.         void onItemClick(String s);  
  169.     }  
  170.   
  171. }  


PinnedHeaderListView.java

[java]  view plain copy
  1. /* 
  2.  * Copyright (C) 2010 The Android Open Source Project 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16.   
  17. package com.example.pinnedheaderlistviewdemo.view;  
  18.   
  19. import android.content.Context;  
  20. import android.graphics.Canvas;  
  21. import android.util.AttributeSet;  
  22. import android.view.View;  
  23. import android.widget.ListAdapter;  
  24. import android.widget.ListView;  
  25.   
  26. /** 
  27.  * A ListView that maintains a header pinned at the top of the list. The 
  28.  * pinned header can be pushed up and dissolved as needed. 
  29.  */  
  30. public class PinnedHeaderListView extends ListView {  
  31.   
  32.     /** 
  33.      * Adapter interface.  The list adapter must implement this interface. 
  34.      */  
  35.     public interface PinnedHeaderAdapter {  
  36.   
  37.         /** 
  38.          * Pinned header state: don't show the header. 
  39.          */  
  40.         public static final int PINNED_HEADER_GONE = 0;  
  41.   
  42.         /** 
  43.          * Pinned header state: show the header at the top of the list. 
  44.          */  
  45.         public static final int PINNED_HEADER_VISIBLE = 1;  
  46.   
  47.         /** 
  48.          * Pinned header state: show the header. If the header extends beyond 
  49.          * the bottom of the first shown element, push it up and clip. 
  50.          */  
  51.         public static final int PINNED_HEADER_PUSHED_UP = 2;  
  52.   
  53.         /** 
  54.          * Computes the desired state of the pinned header for the given 
  55.          * position of the first visible list item. Allowed return values are 
  56.          * {@link #PINNED_HEADER_GONE}, {@link #PINNED_HEADER_VISIBLE} or 
  57.          * {@link #PINNED_HEADER_PUSHED_UP}. 
  58.          */  
  59.         int getPinnedHeaderState(int position);  
  60.   
  61.         /** 
  62.          * Configures the pinned header view to match the first visible list item. 
  63.          * 
  64.          * @param header pinned header view. 
  65.          * @param position position of the first visible list item. 
  66.          * @param alpha fading of the header view, between 0 and 255. 
  67.          */  
  68.         void configurePinnedHeader(View header, int position, int alpha);  
  69.     }  
  70.   
  71.     private static final int MAX_ALPHA = 255;  
  72.   
  73.     private PinnedHeaderAdapter mAdapter;  
  74.     private View mHeaderView;  
  75.     private boolean mHeaderViewVisible;  
  76.   
  77.     private int mHeaderViewWidth;  
  78.   
  79.     private int mHeaderViewHeight;  
  80.   
  81.     public PinnedHeaderListView(Context context) {  
  82.         super(context);  
  83.     }  
  84.   
  85.     public PinnedHeaderListView(Context context, AttributeSet attrs) {  
  86.         super(context, attrs);  
  87.     }  
  88.   
  89.     public PinnedHeaderListView(Context context, AttributeSet attrs, int defStyle) {  
  90.         super(context, attrs, defStyle);  
  91.     }  
  92.   
  93.     public void setPinnedHeaderView(View view) {  
  94.         mHeaderView = view;  
  95.   
  96.         // Disable vertical fading when the pinned header is present  
  97.         // TODO change ListView to allow separate measures for top and bottom fading edge;  
  98.         // in this particular case we would like to disable the top, but not the bottom edge.  
  99.         if (mHeaderView != null) {  
  100.             setFadingEdgeLength(0);  
  101.         }  
  102.         requestLayout();  
  103.     }  
  104.   
  105.     @Override  
  106.     public void setAdapter(ListAdapter adapter) {  
  107.         super.setAdapter(adapter);  
  108.         mAdapter = (PinnedHeaderAdapter)adapter;  
  109.     }  
  110.   
  111.     @Override  
  112.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  113.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  114.         if (mHeaderView != null) {  
  115.             measureChild(mHeaderView, widthMeasureSpec, heightMeasureSpec);  
  116.             mHeaderViewWidth = mHeaderView.getMeasuredWidth();  
  117.             mHeaderViewHeight = mHeaderView.getMeasuredHeight();  
  118.         }  
  119.     }  
  120.   
  121.     @Override  
  122.     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {  
  123.         super.onLayout(changed, left, top, right, bottom);  
  124.         if (mHeaderView != null) {  
  125.             mHeaderView.layout(00, mHeaderViewWidth, mHeaderViewHeight);  
  126.             configureHeaderView(getFirstVisiblePosition());  
  127.         }  
  128.     }  
  129.   
  130.     public void configureHeaderView(int position) {  
  131.         if (mHeaderView == null) {  
  132.             return;  
  133.         }  
  134.   
  135.         int state = mAdapter.getPinnedHeaderState(position);  
  136.         switch (state) {  
  137.             case PinnedHeaderAdapter.PINNED_HEADER_GONE: {  
  138.                 mHeaderViewVisible = false;  
  139.                 break;  
  140.             }  
  141.   
  142.             case PinnedHeaderAdapter.PINNED_HEADER_VISIBLE: {  
  143.                 mAdapter.configurePinnedHeader(mHeaderView, position, MAX_ALPHA);  
  144.                 if (mHeaderView.getTop() != 0) {  
  145.                     mHeaderView.layout(00, mHeaderViewWidth, mHeaderViewHeight);  
  146.                 }  
  147.                 mHeaderViewVisible = true;  
  148.                 break;  
  149.             }  
  150.   
  151.             case PinnedHeaderAdapter.PINNED_HEADER_PUSHED_UP: {  
  152.                 View firstView = getChildAt(0);  
  153.                 int bottom = firstView.getBottom();  
  154.                 int itemHeight = firstView.getHeight();  
  155.                 int headerHeight = mHeaderView.getHeight();  
  156.                 int y;  
  157.                 int alpha;  
  158.                 if (bottom < headerHeight) {  
  159.                     y = (bottom - headerHeight);  
  160.                     alpha = MAX_ALPHA * (headerHeight + y) / headerHeight;  
  161.                 } else {  
  162.                     y = 0;  
  163.                     alpha = MAX_ALPHA;  
  164.                 }  
  165.                 mAdapter.configurePinnedHeader(mHeaderView, position, alpha);  
  166.                 if (mHeaderView.getTop() != y) {  
  167.                     mHeaderView.layout(0, y, mHeaderViewWidth, mHeaderViewHeight + y);  
  168.                 }  
  169.                 mHeaderViewVisible = true;  
  170.                 break;  
  171.             }  
  172.         }  
  173.     }  
  174.   
  175.     @Override  
  176.     protected void dispatchDraw(Canvas canvas) {  
  177.         super.dispatchDraw(canvas);  
  178.         if (mHeaderViewVisible) {  
  179.             drawChild(canvas, mHeaderView, getDrawingTime());  
  180.         }  
  181.     }  
  182. }  


MySectionIndexer.java

[java]  view plain copy
  1. package com.example.pinnedheaderlistviewdemo;  
  2.   
  3. import java.util.Arrays;  
  4.   
  5. import android.util.Log;  
  6. import android.widget.SectionIndexer;  
  7.   
  8. public class MySectionIndexer implements SectionIndexer{  
  9.     private final String[] mSections;//  
  10.     private final int[] mPositions;  
  11.     private final int mCount;  
  12.       
  13.     /** 
  14.      * @param sections 
  15.      * @param counts 
  16.      */  
  17.     public MySectionIndexer(String[] sections, int[] counts) {  
  18.         if (sections == null || counts == null) {  
  19.             throw new NullPointerException();  
  20.         }  
  21.         if (sections.length != counts.length) {  
  22.             throw new IllegalArgumentException(  
  23.                     "The sections and counts arrays must have the same length");  
  24.         }  
  25.         this.mSections = sections;  
  26.         mPositions = new int[counts.length];  
  27.         int position = 0;  
  28.         for (int i = 0; i < counts.length; i++) {  
  29.             if(mSections[i] == null) {  
  30.                 mSections[i] = "";  
  31.             } else {  
  32.                 mSections[i] = mSections[i].trim();   
  33.             }  
  34.               
  35.             mPositions[i] = position;  
  36.             position += counts[i];  
  37.               
  38.             Log.i("MySectionIndexer""counts["+i+"]:"+counts[i]);  
  39.         }  
  40.         mCount = position;  
  41.     }  
  42.       
  43.     @Override  
  44.     public Object[] getSections() {  
  45.         // TODO Auto-generated method stub  
  46.         return mSections;  
  47.     }  
  48.   
  49.     @Override  
  50.     public int getPositionForSection(int section) {  
  51.         //change by lcq 2012-10-12 section > mSections.length以为>=   
  52.         if (section < 0 || section >= mSections.length) {  
  53.             return -1;  
  54.         }  
  55.         return mPositions[section];  
  56.     }  
  57.   
  58.     @Override  
  59.     public int getSectionForPosition(int position) {  
  60.         if (position < 0 || position >= mCount) {  
  61.             return -1;  
  62.         }  
  63.         //注意这个方法的返回值,它就是index<0时,返回-index-2的原因  
  64.         //解释Arrays.binarySearch,如果搜索结果在数组中,刚返回它在数组中的索引,如果不在,刚返回第一个比它大的索引的负数-1  
  65.         //如果没弄明白,请自己想查看api  
  66.         int index = Arrays.binarySearch(mPositions, position);  
  67.         return index >= 0 ? index : -index - 2//当index小于0时,返回-index-2,  
  68.           
  69.     }  
  70.   
  71. }  


CityListAdapter.java

[java]  view plain copy
  1. package com.example.pinnedheaderlistviewdemo.adapter;  
  2.   
  3. import java.util.List;  
  4.   
  5. import android.content.Context;  
  6. import android.view.LayoutInflater;  
  7. import android.view.View;  
  8. import android.view.ViewGroup;  
  9. import android.widget.AbsListView;  
  10. import android.widget.AbsListView.OnScrollListener;  
  11. import android.widget.BaseAdapter;  
  12. import android.widget.TextView;  
  13.   
  14. import com.example.pinnedheaderlistviewdemo.City;  
  15. import com.example.pinnedheaderlistviewdemo.MySectionIndexer;  
  16. import com.example.pinnedheaderlistviewdemo.R;  
  17. import com.example.pinnedheaderlistviewdemo.view.PinnedHeaderListView;  
  18. import com.example.pinnedheaderlistviewdemo.view.PinnedHeaderListView.PinnedHeaderAdapter;  
  19.   
  20. public class CityListAdapter extends BaseAdapter implements  
  21.         PinnedHeaderAdapter, OnScrollListener {  
  22.     private List<City> mList;  
  23.     private MySectionIndexer mIndexer;  
  24.     private Context mContext;  
  25.     private int mLocationPosition = -1;  
  26.     private LayoutInflater mInflater;  
  27.   
  28.     public CityListAdapter(List<City> mList, MySectionIndexer mIndexer,  
  29.             Context mContext) {  
  30.         this.mList = mList;  
  31.         this.mIndexer = mIndexer;  
  32.         this.mContext = mContext;  
  33.         mInflater = LayoutInflater.from(mContext);  
  34.     }  
  35.   
  36.     @Override  
  37.     public int getCount() {  
  38.         // TODO Auto-generated method stub  
  39.         return mList == null ? 0 : mList.size();  
  40.     }  
  41.   
  42.     @Override  
  43.     public Object getItem(int position) {  
  44.         // TODO Auto-generated method stub  
  45.         return mList.get(position);  
  46.     }  
  47.   
  48.     @Override  
  49.     public long getItemId(int position) {  
  50.         // TODO Auto-generated method stub  
  51.         return position;  
  52.     }  
  53.   
  54.     @Override  
  55.     public View getView(int position, View convertView, ViewGroup parent) {  
  56.         View view;  
  57.         ViewHolder holder;  
  58.         if (convertView == null) {  
  59.             view = mInflater.inflate(R.layout.select_city_item, null);  
  60.   
  61.             holder = new ViewHolder();  
  62.             holder.group_title = (TextView) view.findViewById(R.id.group_title);  
  63.             holder.city_name = (TextView) view.findViewById(R.id.city_name);  
  64.   
  65.             view.setTag(holder);  
  66.         } else {  
  67.             view = convertView;  
  68.             holder = (ViewHolder) view.getTag();  
  69.         }  
  70.           
  71.         City city = mList.get(position);  
  72.           
  73.         int section = mIndexer.getSectionForPosition(position);  
  74.         if (mIndexer.getPositionForSection(section) == position) {  
  75.             holder.group_title.setVisibility(View.VISIBLE);  
  76.             holder.group_title.setText(city.getSortKey());  
  77.         } else {  
  78.             holder.group_title.setVisibility(View.GONE);  
  79.         }  
  80.           
  81.         holder.city_name.setText(city.getName());  
  82.   
  83.         return view;  
  84.     }  
  85.   
  86.     public static class ViewHolder {  
  87.         public TextView group_title;  
  88.         public TextView city_name;  
  89.     }  
  90.   
  91.     @Override  
  92.     public int getPinnedHeaderState(int position) {  
  93.         int realPosition = position;  
  94.         if (realPosition < 0  
  95.                 || (mLocationPosition != -1 && mLocationPosition == realPosition)) {  
  96.             return PINNED_HEADER_GONE;  
  97.         }  
  98.         mLocationPosition = -1;  
  99.         int section = mIndexer.getSectionForPosition(realPosition);  
  100.         int nextSectionPosition = mIndexer.getPositionForSection(section + 1);  
  101.         if (nextSectionPosition != -1  
  102.                 && realPosition == nextSectionPosition - 1) {  
  103.             return PINNED_HEADER_PUSHED_UP;  
  104.         }  
  105.         return PINNED_HEADER_VISIBLE;  
  106.     }  
  107.   
  108.     @Override  
  109.     public void configurePinnedHeader(View header, int position, int alpha) {  
  110.         // TODO Auto-generated method stub  
  111.         int realPosition = position;  
  112.         int section = mIndexer.getSectionForPosition(realPosition);  
  113.         String title = (String) mIndexer.getSections()[section];  
  114.         ((TextView) header.findViewById(R.id.group_title)).setText(title);  
  115.     }  
  116.   
  117.     @Override  
  118.     public void onScrollStateChanged(AbsListView view, int scrollState) {  
  119.         // TODO Auto-generated method stub  
  120.   
  121.     }  
  122.   
  123.     @Override  
  124.     public void onScroll(AbsListView view, int firstVisibleItem,  
  125.             int visibleItemCount, int totalItemCount) {  
  126.         // TODO Auto-generated method stub  
  127.         if (view instanceof PinnedHeaderListView) {  
  128.             ((PinnedHeaderListView) view).configureHeaderView(firstVisibleItem);  
  129.         }  
  130.   
  131.     }  
  132. }  



select_city_item.xml

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/group_title"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:background="@color/gray"  
  12.         android:gravity="left|center"  
  13.         android:paddingBottom="5.0dip"  
  14.         android:paddingLeft="@dimen/selectcity_group_item_padding"  
  15.         android:paddingRight="@dimen/selectcity_group_item_padding"  
  16.         android:paddingTop="5.0dip"  
  17.         android:text="S"  
  18.         android:textColor="@color/white"  
  19.         android:textStyle="bold" />  
  20.   
  21.     <TextView  
  22.         android:id="@+id/city_name"  
  23.         android:layout_width="fill_parent"  
  24.         android:layout_height="wrap_content"  
  25.         android:gravity="center_vertical"  
  26.         android:minHeight="40.0dip"  
  27.         android:paddingLeft="@dimen/selectcity_group_item_padding"  
  28.         android:text="深圳"  
  29.         android:textColor="@color/black"  
  30.         android:textSize="15sp" />  
  31.   
  32. </LinearLayout>  


主界面布局文件 activity_main.xml

[html]  view plain copy
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <com.example.pinnedheaderlistviewdemo.view.PinnedHeaderListView  
  8.         android:id="@+id/mListView"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="fill_parent"  
  11.         android:cacheColorHint="@android:color/transparent"  
  12.         android:footerDividersEnabled="false"  
  13.         android:headerDividersEnabled="false" />  
  14.   
  15.     <com.example.pinnedheaderlistviewdemo.view.BladeView  
  16.         android:id="@+id/mLetterListView"  
  17.         android:layout_width="30dp"  
  18.         android:layout_height="fill_parent"  
  19.         android:layout_alignParentRight="true"  
  20.         android:background="#00000000" />  
  21.   
  22. </RelativeLayout>  


MainActivity.java

[java]  view plain copy
  1. package com.example.pinnedheaderlistviewdemo;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.InputStream;  
  6. import java.util.ArrayList;  
  7. import java.util.Collections;  
  8. import java.util.Comparator;  
  9. import java.util.List;  
  10.   
  11. import android.app.Activity;  
  12. import android.os.Bundle;  
  13. import android.os.Environment;  
  14. import android.os.Handler;  
  15. import android.util.Log;  
  16. import android.view.LayoutInflater;  
  17.   
  18. import com.example.pinnedheaderlistviewdemo.adapter.CityListAdapter;  
  19. import com.example.pinnedheaderlistviewdemo.db.CityDao;  
  20. import com.example.pinnedheaderlistviewdemo.db.DBHelper;  
  21. import com.example.pinnedheaderlistviewdemo.view.BladeView;  
  22. import com.example.pinnedheaderlistviewdemo.view.BladeView.OnItemClickListener;  
  23. import com.example.pinnedheaderlistviewdemo.view.PinnedHeaderListView;  
  24.   
  25. public class MainActivity extends Activity {  
  26.       
  27.     private static final int COPY_DB_SUCCESS = 10;  
  28.     private static final int COPY_DB_FAILED = 11;  
  29.     protected static final int QUERY_CITY_FINISH = 12;  
  30.     private MySectionIndexer mIndexer;  
  31.       
  32.     private List<City> cityList = new ArrayList<City>();  
  33.     public static String APP_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test/";  
  34.     private Handler handler = new Handler(){  
  35.   
  36.         public void handleMessage(android.os.Message msg) {  
  37.             switch (msg.what) {  
  38.             case QUERY_CITY_FINISH:  
  39.                   
  40.                 if(mAdapter==null){  
  41.                       
  42.                     mIndexer = new MySectionIndexer(sections, counts);  
  43.                       
  44.                     mAdapter = new CityListAdapter(cityList, mIndexer, getApplicationContext());  
  45.                     mListView.setAdapter(mAdapter);  
  46.                       
  47.                     mListView.setOnScrollListener(mAdapter);  
  48.                       
  49.                     //設置頂部固定頭部  
  50.                     mListView.setPinnedHeaderView(LayoutInflater.from(getApplicationContext()).inflate(    
  51.                             R.layout.list_group_item, mListView, false));    
  52.                       
  53.                 }else if(mAdapter!=null){  
  54.                     mAdapter.notifyDataSetChanged();  
  55.                 }  
  56.                   
  57.                 break;  
  58.   
  59.             case COPY_DB_SUCCESS:  
  60.                 requestData();  
  61.                 break;  
  62.             default:  
  63.                 break;  
  64.             }  
  65.         };  
  66.     };  
  67.     private DBHelper helper;  
  68.   
  69.     private CityListAdapter mAdapter;  
  70.     private static final String ALL_CHARACTER = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;  
  71.     protected static final String TAG = null;  
  72.       
  73.     private String[] sections = { "#""A""B""C""D""E""F""G""H""I""J""K",  
  74.             "L""M""N""O""P""Q""R""S""T""U""V""W""X",  
  75.             "Y""Z" };  
  76.     private int[] counts;  
  77.     private PinnedHeaderListView mListView;  
  78.       
  79.     @Override  
  80.     protected void onCreate(Bundle savedInstanceState) {  
  81.         super.onCreate(savedInstanceState);  
  82.         setContentView(R.layout.activity_main);  
  83.           
  84.         helper = new DBHelper();  
  85.           
  86.         copyDBFile();  
  87.         findView();  
  88.     }  
  89.   
  90.     private void copyDBFile() {  
  91.           
  92.         File file = new File(APP_DIR+"/city.db");  
  93.         if(file.exists()){  
  94.             requestData();  
  95.               
  96.         }else{  //拷贝文件  
  97.             Runnable task = new Runnable() {  
  98.                   
  99.                 @Override  
  100.                 public void run() {  
  101.                       
  102.                     copyAssetsFile2SDCard("city.db");  
  103.                 }  
  104.             };  
  105.               
  106.             new Thread(task).start();  
  107.         }  
  108.     }  
  109.       
  110.     /** 
  111.      * 拷贝资产目录下的文件到 手机 
  112.      */  
  113.     private void copyAssetsFile2SDCard(String fileName) {  
  114.           
  115.         File desDir = new File(APP_DIR);  
  116.         if (!desDir.exists()) {  
  117.             desDir.mkdirs();  
  118.         }  
  119.   
  120.         // 拷贝文件  
  121.         File file = new File(APP_DIR + fileName);  
  122.         if (file.exists()) {  
  123.             file.delete();  
  124.         }  
  125.   
  126.         try {  
  127.             InputStream in = getAssets().open(fileName);  
  128.   
  129.             FileOutputStream fos = new FileOutputStream(file);  
  130.   
  131.             int len = -1;  
  132.             byte[] buf = new byte[1024];  
  133.             while ((len = in.read(buf)) > 0) {  
  134.                 fos.write(buf, 0, len);  
  135.             }  
  136.   
  137.             fos.flush();  
  138.             fos.close();  
  139.               
  140.             handler.sendEmptyMessage(COPY_DB_SUCCESS);  
  141.         } catch (Exception e) {  
  142.             e.printStackTrace();  
  143.             handler.sendEmptyMessage(COPY_DB_FAILED);  
  144.         }  
  145.     }  
  146.   
  147.     private void requestData() {  
  148.           
  149.         Runnable task = new Runnable() {  
  150.               
  151.             @Override  
  152.             public void run() {  
  153.                 CityDao dao = new CityDao(helper);  
  154.                   
  155.                 List<City> hot = dao.getHotCities();  //热门城市  
  156.                 List<City> all = dao.getAllCities();  //全部城市  
  157.                   
  158.                 if(all!=null){  
  159.                       
  160.                     Collections.sort(all, new MyComparator());  //排序  
  161.                       
  162.                     cityList.addAll(hot);  
  163.                     cityList.addAll(all);  
  164.                       
  165.                     //初始化每个字母有多少个item  
  166.                     counts = new int[sections.length];  
  167.                       
  168.                     counts[0] = hot.size(); //热门城市 个数  
  169.                       
  170.                     for(City city : all){   //计算全部城市  
  171.                           
  172.                         String firstCharacter = city.getSortKey();  
  173.                         int index = ALL_CHARACTER.indexOf(firstCharacter);  
  174.                         counts[index]++;  
  175.                     }  
  176.                       
  177.                     handler.sendEmptyMessage(QUERY_CITY_FINISH);  
  178.                 }  
  179.             }  
  180.         };  
  181.           
  182.         new Thread(task).start();  
  183.     }  
  184.       
  185.     public class MyComparator implements Comparator<City> {  
  186.   
  187.         @Override  
  188.         public int compare(City c1, City c2) {  
  189.   
  190.             return c1.getSortKey().compareTo(c2.getSortKey());  
  191.         }  
  192.   
  193.     }  
  194.   
  195.     private void findView() {  
  196.           
  197.         mListView = (PinnedHeaderListView) findViewById(R.id.mListView);  
  198.         BladeView mLetterListView = (BladeView) findViewById(R.id.mLetterListView);  
  199.           
  200.         mLetterListView.setOnItemClickListener(new OnItemClickListener() {  
  201.               
  202.             @Override  
  203.             public void onItemClick(String s) {  
  204.                 if(s!=null){  
  205.                       
  206.                     int section = ALL_CHARACTER.indexOf(s);  
  207.                       
  208.                     int position = mIndexer.getPositionForSection(section);  
  209.                       
  210.                     Log.i(TAG, "s:"+s+",section:"+section+",position:"+position);  
  211.                       
  212.                     if(position!=-1){  
  213.                         mListView.setSelection(position);  
  214.                     }else{  
  215.                           
  216.                     }  
  217.                 }  
  218.                   
  219.             }  
  220.         });  
  221.     }  
  222.   
  223. }  





OK,就这么多了,另附工程源码下载地址:http://download.csdn.net/detail/fx_sky/5995355

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值