• 熱門專題

字母條索引定位

作者:  發布日期:2015-06-05 22:31:15
Tag標簽:字母  索引  
  • activity_main.xml

     

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <ListView
            android:id="@+id/listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        </ListView>
    
        <com.atguigu.quickindex.QuickIndexBar
            android:id="@+id/qucikIndexBar"
            android:layout_width="35dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:background="#CFCFCF" />
    
        <TextView
            android:id="@+id/currentIndex"
            android:layout_width="120dp"
            android:layout_height="105dp"
            android:layout_centerInParent="true"
            android:background="@drawable/bg_index"
            android:gravity="center"
            android:text="A"
            android:textColor="#ffffff"
            android:textSize="30sp"
            android:visibility="gone" />
    </RelativeLayout>

    item_friend.xml

     

     

    <?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="wrap_content"
        android:orientation="vertical" >
        
        <TextView 
            android:id="@+id/index"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:paddingLeft="10dp"
            android:text="A"
            android:textColor="#ffffff"
            android:background="#666666"
            android:textSize="18sp"/>
        <TextView 
            android:id="@+id/name"
            android:layout_height="wrap_content"
           	android:layout_width="match_parent"
           	android:padding="10dp"
            android:text="adasd"
            android:textColor="#666666"
            android:textSize="20sp"/>
    </LinearLayout>

    MainActivity

     

     

    package com.atguigu.quickindex;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ListView;
    import android.widget.TextView;
    
    import com.atguigu.quickindex.QuickIndexBar.OnTouchIndexChange;
    
    public class MainActivity extends Activity {
    
    	private ListView listView;
    	private QuickIndexBar qucikIndexBar;
    	private TextView currentIndex;
    	// 數據集合
    	private List<Friend> friends = new ArrayList<Friend>();
    	// 適配器
    	private FriendAdapter adapter;
    	private Handler handler = new Handler();
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		// 加載主布局
    		setContentView(R.layout.activity_main);
    		// 初始化控件
    		init();
    	}
    
    	private void init() {
    		/** 初始化布局視圖 */
    		listView = (ListView) findViewById(R.id.listview);
    		qucikIndexBar = (QuickIndexBar) findViewById(R.id.qucikIndexBar);
    		currentIndex = (TextView) findViewById(R.id.currentIndex);
    		/** 初始化數據 */
    		initData();
    		// 創建適配器
    		adapter = new FriendAdapter();
    		// 設置適配器
    		listView.setAdapter(adapter);
    
    		// 設置觸摸的字母變化的監聽
    		qucikIndexBar.setOnTouchIndexChange(new OnTouchIndexChange() {
    			@Override
    			public void onChange(String word) {// word為當前觸摸的字母
    				// 顯示當前觸摸的字母
    				showInexWord(word);
    				// 使用列表定位到對應的列表項
    				locationWord(word);
    			}
    		});
    	}
    
    	private void locationWord(String word) {
    		for (int i = 0; i < friends.size(); i++) {
    			//名字首字母
    			String firstWord = friends.get(i).getPinyin().charAt(0) + "";
    			if (firstWord.equals(word)) {
    				//定位到item的位置
    				listView.setSelection(i);
    				return;
    			}
    		}
    	}
    
    	private void showInexWord(String word) {
    		currentIndex.setVisibility(View.VISIBLE);
    		currentIndex.setText(word);
    		//停掉所用handler的消息,防止內存泄露
    		handler.removeCallbacksAndMessages(null);
    		//2秒的定時器
    		handler.postDelayed(new Runnable() {
    			@Override
    			public void run() {
    				currentIndex.setVisibility(View.GONE);
    			}
    		}, 2000);
    	}
    
    	private void initData() {
    		// 虛擬數據
    		friends.add(new Friend("張曉飛"));
    		friends.add(new Friend("楊光福"));
    		friends.add(new Friend("胡繼群"));
    		friends.add(new Friend("劉暢"));
    
    		friends.add(new Friend("鐘澤興"));
    		friends.add(new Friend("尹革新"));
    		friends.add(new Friend("安傳鑫"));
    		friends.add(new Friend("張騫壬"));
    
    		friends.add(new Friend("溫松"));
    		friends.add(new Friend("李鳳秋"));
    		friends.add(new Friend("劉甫"));
    		friends.add(new Friend("婁全超"));
    		friends.add(new Friend("張猛"));
    
    		friends.add(new Friend("王英杰"));
    		friends.add(new Friend("李振南"));
    		friends.add(new Friend("孫仁政"));
    		friends.add(new Friend("唐春雷"));
    		friends.add(new Friend("牛鵬偉"));
    		friends.add(new Friend("姜宇航"));
    
    		friends.add(new Friend("劉挺"));
    		friends.add(new Friend("張洪瑞"));
    		friends.add(new Friend("張建忠"));
    		friends.add(new Friend("侯亞帥"));
    		friends.add(new Friend("劉帥"));
    
    		friends.add(new Friend("喬競飛"));
    		friends.add(new Friend("徐雨健"));
    		friends.add(new Friend("吳亮"));
    		friends.add(new Friend("王兆霖"));
    
    		friends.add(new Friend("阿三"));
    		friends.add(new Friend("二毛"));
    
    		/**
    		 * Comparable。可以讓自定義對象實現一個Comparable接口,這個接口只有一個方法comparableTo(Object o)
    		 * 
    		 * 其規則是當前對象與o對象進行比較,返回一個int值,系統根據此值進行排序。
    		 * 
    		 * 如當前對象>o對象,則返回值>0;
    		 * 
    		 * 如當前對象=o對象,則返回值=0;
    		 * 
    		 * 如當前對象<o對象,則返回值<0;
    		 */
    		Collections.sort(friends);
    	}
    
    	/**
    	 * adapter
    	 */
    	class FriendAdapter extends BaseAdapter {
    
    		@Override
    		public int getCount() {
    			return friends.size();
    		}
    
    		@Override
    		public Object getItem(int position) {
    			return friends.get(position);
    		}
    
    		@Override
    		public long getItemId(int position) {
    			return 0;
    		}
    
    		@Override
    		public View getView(int position, View convertView, ViewGroup parent) {
    			ViewHolder holder = null;
    			if (convertView == null) {
    				convertView = View.inflate(getApplicationContext(),
    						R.layout.item_friend, null);
    				holder = new ViewHolder();
    				holder.index = (TextView) convertView.findViewById(R.id.index);
    				holder.name = (TextView) convertView.findViewById(R.id.name);
    				convertView.setTag(holder);
    			} else {
    				holder = (ViewHolder) convertView.getTag();
    			}
    
    			Friend friend = friends.get(position);
    			String firstWord = friend.getPinyin().charAt(0) + "";// 得到拼音首字母
    
    			if (position == 0) {// 如果是第一個, 顯示首字母View
    				holder.index.setVisibility(View.VISIBLE);
    			} else {// 如果不是第一個
    				// 上一項的拼音首字母
    				String preFirstWord = friends.get(position - 1).getPinyin()
    						.charAt(0)
    						+ "";
    				if (firstWord.equals(preFirstWord)) {// 如果當前的與上一個相同, 不顯示首字母View
    					holder.index.setVisibility(View.GONE);
    				} else {// 否則, 顯示
    					holder.index.setVisibility(View.VISIBLE);
    				}
    			}
    
    			holder.index.setText(firstWord);
    			holder.name.setText(friend.getName());
    
    			return convertView;
    		}
    
    		class ViewHolder {
    			TextView index, name;
    		}
    	}
    }
    

    QuickIndexBar

     

     

    package com.atguigu.quickindex;
    
    import android.annotation.SuppressLint;
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Rect;
    import android.graphics.Typeface;
    import android.util.AttributeSet;
    import android.view.MotionEvent;
    import android.view.View;
    
    /**
     * 自定義快速索引的View
     */
    public class QuickIndexBar extends View {
    
    	public QuickIndexBar(Context context, AttributeSet attrs) {
    		super(context, attrs);
    		// 初始化paint
    		paint = new Paint();
    		paint.setAntiAlias(true);// 抗據齒
    	}
    
    	private Paint paint;
    
    	// 字母的寬、高
    	private int cellWidth;
    	private int cellHeight;
    	private int touchIndex = -1;
    	// 字體選中、非選中大小
    	private int textSize;
    	private int textTouchSize;
    
    	private String[] indexArr = { "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" };
    
    	@Override
    	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
    		cellWidth = this.getMeasuredWidth();
    		cellHeight = this.getMeasuredHeight() / indexArr.length;
    
    		textSize = cellHeight - 5;
    		textTouchSize = cellHeight + 5;
    	}
    
    	@SuppressLint("DrawAllocation")
    	@Override
    	protected void onDraw(Canvas canvas) {
    		super.onDraw(canvas);
    
    		for (int i = 0; i < indexArr.length; i++) {
    			// 字母的字體大小
    			paint.setTextSize(i == touchIndex ? textTouchSize : textSize);
    			// 字母的字體顏色
    			paint.setColor(i == touchIndex ? Color.parseColor("#666666")
    					: Color.WHITE);
    			// 計算字母顯示的寬高
    			Rect bounds = new Rect();
    			//paint.getTextBounds(str, 0, str.length(), rect); 
    			paint.getTextBounds(indexArr[i], 0, 1, bounds);
    			int width = bounds.width();
    			int height = bounds.height();
    			// 計算字母繪制的坐標
    			float x = cellWidth / 2 - width / 2;
    			float y = i * cellHeight + cellHeight / 2 + height / 2;
    			// 繪制字母文本
    			canvas.drawText(indexArr[i], x, y, paint);
    		}
    	}
    
    	@Override
    	public boolean onTouchEvent(MotionEvent event) {
    
    		// 相對于當前View的事件y坐標
    		int y = (int) event.getY();
    
    		switch (event.getAction()) {
    		case MotionEvent.ACTION_DOWN:
    		case MotionEvent.ACTION_MOVE:
    			// 如果沒有在當前字母的區域內, 就需要更新touchIndex, 并重繪
    			int index = y / cellHeight;
    			if (index != touchIndex) {
    				touchIndex = index;
    				if (touchIndex >= indexArr.length)
    					touchIndex = indexArr.length - 1;
    				// 強制重繪
    				invalidate();
    				// 如果有監聽器, 調用監聽器的回調方法
    				if (onTouchIndexChange != null) {
    					onTouchIndexChange.onChange(indexArr[touchIndex]);
    				}
    			}
    			break;
    		case MotionEvent.ACTION_UP:
    			touchIndex = -1;
    			// 強制重繪
    			invalidate();
    			break;
    		default:
    			break;
    		}
    		return true;
    	}
    
    	private OnTouchIndexChange onTouchIndexChange;
    
    	public void setOnTouchIndexChange(OnTouchIndexChange onTouchIndexChange) {
    		this.onTouchIndexChange = onTouchIndexChange;
    	}
    
    	public interface OnTouchIndexChange {
    		public void onChange(String word);
    	}
    }
    

    Friend

     

     

    package com.atguigu.quickindex;
    
    /**
     * 好友信息對象
     */
    public class Friend implements Comparable<Friend> {
    
    	private String name;//姓名
    	private String pinyin;//姓名對應的拼音
    
    	public Friend(String name) {
    		super();
    		this.name = name;
    		//通過名字得到對應的拼音
    		this.pinyin = PinYinUtils.getPinYin(name);
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public String getPinyin() {
    		return pinyin;
    	}
    
    	public void setPinyin(String pinyin) {
    		this.pinyin = pinyin;
    	}
    
    	@Override
    	public String toString() {
    		return "Friend [name=" + name + ", pinyin=" + pinyin + "]";
    	}
    
    	/**
    	 * 此接口強行對實現它的每個類的對象進行整體排序。此排序被稱為該類的自然排序 ,類的 compareTo 方法被稱為它的自然比較方法 。
    	 */
    	@Override
    	public int compareTo(Friend another) {
    		return pinyin.compareTo(another.getPinyin());
    	}
    }
    

    PinYinUtils

     

     

    package com.atguigu.quickindex;
    
    import net.sourceforge.pinyin4j.PinyinHelper;
    import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
    import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
    import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
    import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
    
    /**
     * 將漢字轉換為拼音
     */
    public class PinYinUtils {
    	/**
    	 * 得到指定漢字的拼音
    	 * 注意:不應該被頻繁調用,它消耗一定內存
    	 */
    	public static String getPinYin(String hanzi){
    		String pinyin = "";
    		
    		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();//控制轉換是否大小寫,是否帶音標
    		format.setCaseType(HanyuPinyinCaseType.UPPERCASE);//大寫
    		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    		
    		//由于不能直接對多個漢字轉換,只能對單個漢字轉換
    		char[] arr = hanzi.toCharArray();
    		for (int i = 0; i < arr.length; i++) {
    			if(Character.isWhitespace(arr[i]))continue;//如果是空格,則不處理,進行下次遍歷
    			
    			//漢字是2個字節存儲,肯定大于127,所以大于127就可以當為漢字轉換
    			if(arr[i]>127){
    				try {
    					//由于多音字的存在,單 dan shan
    					String[] pinyinArr = PinyinHelper.toHanyuPinyinStringArray(arr[i], format);
    					
    					if(pinyinArr!=null){
    						pinyin += pinyinArr[0];
    					}else {
    						pinyin += arr[i];
    					}
    				} catch (BadHanyuPinyinOutputFormatCombination e) {
    					e.printStackTrace();
    					//不是正確的漢字
    					pinyin += arr[i];
    				}
    			}else {
    				//不是漢字,
    				pinyin += arr[i];
    			}
    		}
    		return pinyin;
    	}
    }
    

     

About IT165 - 廣告服務 - 隱私聲明 - 版權申明 - 免責條款 - 網站地圖 - 網友投稿 - 聯系方式
本站內容來自于互聯網,僅供用于網絡技術學習,學習中請遵循相關法律法規
彩票联盟网站贵溪市| 闸北区|