android仿微信通讯录字母索引控件

来源:互联网 发布:网络改编歌曲 编辑:程序博客网 时间:2024/05/22 03:02

最近在项目中用到关于字母索引的功能(类似微信联系人索引功能),在网上都是千篇一律的例子,通常都是通过实现SectionIndexer,闲来之时按照自己的方法写了一个,现分享。

1.自定义字母索引控件LetterIndexView.java,代码如下:

/** * 自定义字母索引控件 * @author galesnjak * @date 2014年2月24日 */public class LetterIndexView extends View { /**  * 索引字符串数组  */ private String[] arrays = new String[] { "★", "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", "#" };  private int width;//字母索引控件宽度 private int height;//字母索引控件高度 private boolean isDown = false;// 标识是否按下,用作改变控件背景色 private int oldSelect = -1;//上次选中项索引  private int textsize;//画笔字体大小  private ListView listView;//绑定ListView private TextView overlay;//当前索引显示框   public LetterIndexView(Context context) {  super(context);  initIndexView(context,null, 0); } public LetterIndexView(Context context, AttributeSet attrs) {  super(context, attrs);  initIndexView(context,attrs, 0); } public LetterIndexView(Context context, AttributeSet attrs, int defStyle) {  super(context, attrs, defStyle);  initIndexView(context,attrs, defStyle); }  /**  * 该方法的作用:初始化索引控件  * @author galesnjak  * @date 2014年2月24日  * @param context  * @param attrs  * @param defStyle  */ private void initIndexView(Context context,AttributeSet attrs, int defStyle){  initOverlay(context);    TypedArray typedArray = getContext().obtainStyledAttributes(attrs,R.styleable.LetterIndexPaint,defStyle,0);  if(typedArray != null){   textsize = typedArray.getInt(R.styleable.LetterIndexPaint_textsize, 12);   typedArray.recycle();  } }  /**  * 该方法的作用:初始化当前索引显示框  * @author galesnjak  * @date 2014年2月24日  * @param context  */ private void initOverlay(Context context) {  LayoutInflater inflater = LayoutInflater.from(context);  overlay = (TextView) inflater.inflate(R.layout.overlay_layout, null);  overlay.setVisibility(View.INVISIBLE);  WindowManager.LayoutParams lp = new WindowManager.LayoutParams(    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,    WindowManager.LayoutParams.TYPE_APPLICATION,    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE      | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,    PixelFormat.TRANSLUCENT);  WindowManager windowManager = (WindowManager) context    .getSystemService(Context.WINDOW_SERVICE);  windowManager.addView(overlay, lp); }  /**  * 该方法的作用:设置ListView绑定  * @author galesnjak  * @date 2014年2月24日  * @param listView  */ public void setListView(ListView listView){  this.listView = listView; } @Override public boolean dispatchTouchEvent(MotionEvent event) {  int action = event.getAction();  float y = event.getY();  int c = (int) (y / getHeight() * arrays.length);  if(c < 0 || c > arrays.length){   return false;  }  switch (action) {  case MotionEvent.ACTION_DOWN:   isDown = true;   setSelection(c);   break;  case MotionEvent.ACTION_UP:   isDown = false;   overlay.setVisibility(View.INVISIBLE);   invalidate();   break;  case MotionEvent.ACTION_MOVE:   setSelection(c);   break;  }  return true; }  /**  * 该方法的作用:控件核心代码 ,通过索引设置选中项  * @author hWX180656 hulimin  * @date 2014年2月24日  * @param index  */ private void setSelection(int index){  if(index < 0 || index > arrays.length){   return;  }  oldSelect = index;  overlay.setText(arrays[index]);  overlay.setVisibility(View.VISIBLE);  if(listView != null && listView.getAdapter() != null){   if(listView.getAdapter() instanceof ILetterIndexer){    ILetterIndexer letterIndexer = (ILetterIndexer) listView.getAdapter();    //获取选中索引在listView中位置(position)    int position = letterIndexer.getPositionForSection(arrays[index]);    listView.setSelection(position);   }  }  invalidate(); }  @Override protected void onDraw(Canvas canvas) {  super.onDraw(canvas);  if (isDown) {   canvas.drawColor(Color.parseColor("#40000000"));  }  width = getWidth();  height = getHeight();  Paint paint = new Paint();  paint.setTextSize(textsize);  paint.setAntiAlias(true);  for (int i = 0; i < arrays.length; i++) {   if(i == oldSelect){    paint.setColor(Color.BLUE);   }else{    paint.setColor(Color.RED);   }   float xPos = width / 2 - paint.measureText(arrays[i]) / 2;   float yPos = height / arrays.length * (i + 1);   canvas.drawText(arrays[i], xPos, yPos, paint);  } }}

2.通过实现SectionIndexer,本人感觉太受限制,故自定义接口ILetterIndex.java,代码如下:

public interface ILetterIndexer {int getPositionForSection(String section);}


3.vo

public class People {public String name;public String sortLetter;public People(String name, String sortLetter) {super();this.name = name;this.sortLetter = sortLetter;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSortLetter() {return sortLetter;}public void setSortLetter(String sortLetter) {this.sortLetter = sortLetter;}}


4.案例通过ListView和自定义LetterIndexView一起实现,适配器LetterIndexAdapter.java,代码如下:

public class LetterIndexAdapter extends BaseAdapter implements ILetterIndexer {List<People> peoples;Context context;HashMap<String, Integer> hashMap;public LetterIndexAdapter(List<People> peoples,Context context,HashMap<String, Integer> hashMap){this.context = context;this.peoples = peoples;this.hashMap = hashMap;}@Overridepublic int getCount() {return peoples != null ? peoples.size() : 0;}@Overridepublic Object getItem(int position) {return peoples.get(position);}@Overridepublic long getItemId(int position) {return 0;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {viewHolder holder;if (convertView == null) {convertView =LayoutInflater.from(context).inflate(R.layout.friend_item, null);holder = new viewHolder();holder.friend_letter = (TextView) convertView.findViewById(R.id.friend_letter);holder.friend_name = (TextView) convertView.findViewById(R.id.friend_item_name);convertView.setTag(holder);} else {holder = (viewHolder) convertView.getTag();}People people = peoples.get(position);System.out.println("getView:"+String.valueOf(people.sortLetter));if(!hashMap.containsKey(String.valueOf(people.sortLetter))){hashMap.put(String.valueOf(people.sortLetter), position);}holder.friend_name.setText(people.name);String currentLetter = String.valueOf(people.sortLetter);String lastLetter = String.valueOf((position - 1) > 0 ? (String.valueOf(peoples.get(position - 1).sortLetter)) : "");if (!lastLetter.equals(currentLetter)) {holder.friend_letter.setText(currentLetter);holder.friend_letter.setVisibility(View.VISIBLE);} else {holder.friend_letter.setVisibility(View.GONE);}return convertView;}public class viewHolder {TextView friend_letter;ImageView friend_logo;TextView friend_name;}@Overridepublic int getPositionForSection(String section) {if(!TextUtils.isEmpty(section)){if(hashMap.containsKey(section)){return hashMap.get(section);}}return -1;}}


5.MainActivity.java代码如下:

public class MainActivity extends Activity {private List<People> peoples; HashMap<String, Integer> hashMap = new HashMap<String, Integer>(); @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.activity_main);initData();initView();}private void initView() {LetterIndexView indexView = (LetterIndexView) findViewById(R.id.index);ListView listView = (ListView) findViewById(R.id.listview);indexView.setListView(listView);listView.setAdapter(new LetterIndexAdapter(peoples,this,hashMap));}private void initData() {peoples = new ArrayList<People>(); peoples.add(new People("星星", "★"));peoples.add(new People("阿杜", "A"));peoples.add(new People("阿妹", "A"));peoples.add(new People("必读克", "B"));peoples.add(new People("逼哥", "B"));peoples.add(new People("chendong", "C"));peoples.add(new People("heqiang", "H"));peoples.add(new People("xusong", "X"));peoples.add(new People("yangjing", "Y"));peoples.add(new People("外星人", "#"));for(int i = 0;i<peoples.size();i++){if(!hashMap.containsKey(String.valueOf(peoples.get(i).sortLetter))){hashMap.put(String.valueOf(peoples.get(i).sortLetter),i);}}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);return true;}}


5.res/layout/activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:index="http://schemas.android.com/apk/res/com.huawei.letterindex"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <ListView        android:id="@+id/listview"        android:layout_width="fill_parent"        android:layout_height="fill_parent" >    </ListView>    <com.huawei.letterindex.LetterIndexView        android:id="@+id/index"        android:layout_width="25dip"        android:layout_height="fill_parent"        android:layout_alignParentRight="true"        index:textsize="25" /></RelativeLayout>


6.res/layout/friend_item.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <RelativeLayout        android:id="@+id/friend_rl_item_1"        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <TextView            android:id="@+id/friend_letter"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:layout_alignParentLeft="true"            android:layout_centerVertical="true"            android:background="@drawable/schoolcity_bg1"            android:paddingLeft="18dp"            android:text="A"            android:textSize="20sp" />    </RelativeLayout>    <RelativeLayout        android:id="@+id/friend_rl_item_2"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:background="@drawable/friend_item_selector" >        <ImageView            android:id="@+id/friend_item_logo"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerVertical="true"            android:layout_marginLeft="10dp"            android:src="@drawable/dashi" />        <TextView            android:id="@+id/friend_item_name"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerVertical="true"            android:layout_marginLeft="15dp"            android:layout_toRightOf="@+id/friend_item_logo"            android:text="Galesnjak"            android:textSize="20sp" />        <ImageView            android:id="@+id/friend_item_image_2"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:layout_centerVertical="true"            android:layout_marginRight="10dp"            android:src="@drawable/sportsmain_item_righicon" />    </RelativeLayout></LinearLayout>


7.overlay_layout.xml

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"    android:background="@drawable/view_shape"    android:gravity="center"    android:maxHeight="80dip"    android:maxWidth="80dip"    android:minHeight="80dip"    android:minWidth="80dip"    android:padding="5dip"    android:textColor="#3399ff"    android:textSize="50sp" />


8.res/values/attrs.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="LetterIndexPaint">        <attr name="textsize" format="integer"/>    </declare-styleable></resources>


9.res/drawable/view_shape.xml

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" >    <solid android:color="#cc0000" />    <stroke  android:width="1dp"  android:color="#ffffff" />  <corners  android:radius="5dp" />  <padding  android:left="0dp"  android:top="0dp"  android:right="0dp"  android:bottom="0dp" /></shape>


10.res/drawable/friend_item_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:drawable="@drawable/listitem_bg" android:state_enabled="false"/>    <item android:drawable="@drawable/listitem_p_bg" android:state_focused="true"></item>    <item android:drawable="@drawable/listitem_p_bg" android:state_pressed="true"></item></selector>


11.其他资源图片未上传,不好意思。

1 0
原创粉丝点击