Android 自定義view 快速檢索

首先想要做出快速檢索的效果主要的是思路

1.快速檢索是每個(gè)字母都能點(diǎn) 而且是豎向排序 所以我們首先想到的做法 就是listview? 但是用系統(tǒng)的listview是實(shí)現(xiàn)不了我們的效果的? 所以實(shí)現(xiàn)這個(gè)功能是自定義的listview。

創(chuàng)建一個(gè)類繼承l(wèi)istview


重寫view的三個(gè)構(gòu)造方法

一個(gè)參數(shù)的構(gòu)造方法在new 對(duì)象時(shí)候調(diào)用

二個(gè)參數(shù)構(gòu)造方法是在布局中聲明此控件的時(shí)候調(diào)用

三個(gè)參數(shù)構(gòu)造方法是在布局中聲明并且用到style屬性時(shí)調(diào)用

完成之后我們就該進(jìn)行下一步操作了

在init()中創(chuàng)建畫筆


重寫onFinishInflate()、onSizeChanged()、onLayout()、onMeasure()、onDraw()、onTouchEvent()方法。用于測(cè)量、繪制、監(jiān)聽手勢(shì)等功能

具體代碼如下:


@Override

? ? protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

}

@Override

? ? protected void onDraw(Canvas canvas) {

for (int i =0; i

int x =width /2;

float y =callHeight/2+getTextHeight(list[i])/2+i*callHeight;

canvas.drawText(list[i],x,y,paint);

}

super.onDraw(canvas);

}

private float getTextHeight(String s) {

Rect rect =new Rect();

paint.getTextBounds(s,0,1,rect);

return rect.height();

}

private int mIndex=-1;

@Override

? ? public boolean onTouchEvent(MotionEvent event) {

switch (event.getAction()){

case MotionEvent.ACTION_DOWN:

case MotionEvent.ACTION_MOVE:

float y = event.getY();

int index = (int) (y /callHeight);

if(mIndex!=index){

String s =list[index];

if(getData!=null){

getData.getData(s);

}

}

mIndex=index;

invalidate();

break;

case MotionEvent.ACTION_UP:

mIndex=-1;

break;

}

return super.onTouchEvent(event);

}

public interface GetData{

void getData(String s);

}

其中g(shù)etdata接口為回掉接口用于回掉手勢(shì)事件

好一個(gè)簡(jiǎn)單的自定義view快速檢索就實(shí)現(xiàn)了!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容