先給大家展示下效果圖:
實(shí)現(xiàn)代碼如下:
下面簡(jiǎn)單說(shuō)下實(shí)現(xiàn)原理。
public class IndexBar extends LinearLayout implements View.OnTouchListener { private static final String[] INDEXES = 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 static final int TOUCHED_BACKGROUND_COLOR = 0x40000000; private OnIndexChangedListener mListener; public void setOnIndexChangedListener(OnIndexChangedListener listener) { mListener = listener; } public IndexBar(Context context) { this(context, null); } public IndexBar(Context context, AttributeSet attrs) { this(context, attrs, 0); } public IndexBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } private void init(AttributeSet attrs) { TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.IndexBar); float indexTextSize = ta.getDimension(R.styleable.IndexBar_indexTextSize, Utils.sp2px(getContext(), 12)); int indexTextColor = ta.getColor(R.styleable.IndexBar_indexTextColor, 0xFF616161); ta.recycle(); setOrientation(VERTICAL); setOnTouchListener(this); for (String index : INDEXES) { TextView text = new TextView(getContext()); text.setText(index); text.setTextSize(TypedValue.COMPLEX_UNIT_PX, indexTextSize); text.setTextColor(indexTextColor); text.setGravity(Gravity.CENTER); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1); text.setLayoutParams(params); addView(text); } } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: setBackgroundColor(TOUCHED_BACKGROUND_COLOR); handle(v, event); return true; case MotionEvent.ACTION_MOVE: handle(v, event); return true; case MotionEvent.ACTION_UP: setBackgroundColor(Color.TRANSPARENT); handle(v, event); return true; } return super.onTouchEvent(event); } private void handle(View v, MotionEvent event) { int y = (int) event.getY(); int height = v.getHeight(); int position = INDEXES.length * y / height; if (position < 0) { position = 0; } else if (position >= INDEXES.length) { position = INDEXES.length - 1; } String index = INDEXES[position]; boolean showIndicator = event.getAction() != MotionEvent.ACTION_UP; if (mListener != null) { mListener.onIndexChanged(index, showIndicator); } } public interface OnIndexChangedListener { void onIndexChanged(String index, boolean showIndicator); } }
當(dāng)前文章:Android仿微信通訊錄滑動(dòng)快速定位功能-創(chuàng)新互聯(lián)
本文鏈接:http://www.rwnh.cn/article26/jogcg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供云服務(wù)器、響應(yīng)式網(wǎng)站、電子商務(wù)、企業(yè)建站、域名注冊(cè)、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容