android 自定義26個字母控件

效果圖


letter.png

選擇和滑動的時候屏幕中間會顯示選擇的字母耿芹。

  • 一 是測量這個控件的寬高崭篡,在onMeasure方法中
    //獲取控件寬度,通過畫筆測量字母A來得到字母寬度吧秕,再加上左右的padding
    widthSize=mPaint.measureText("A")+getPadingLeft+getPaddingRight;
    //get 控件height,因為這個控件在layout文件里高度需要設(shè)置MatchParent琉闪,
    所以直接從measuespec中獲取高度
    heightSize=MeasureSpec.getHightSize(heghtMeasureSpec);

  • 二 onDraw
    //需要繪制26個字母,所以這里寫個for循環(huán)
    itemHight=(getHight-getPaddingTop)/26;//each letter height
    //繪制字母的基線位置
    baselineY=itemHeight/2+(metrcis.bottom-metrics.top)/2-metrics.bottom;
    for(int i=0;i<letterArray.length;i++){
    x=getWidth/2-mPaint.measureText(letterArray[i])/2;//x的坐標(biāo)
    y=itemHight*i+baselineY;
    if(i==currentLetterpostion)
    canvas.drawText(letterArray[i],x,y,mSelectPaint);//繪制選中文字
    else
    canvas.drawText(letterArray[i],x,y,mNormalPaint);//繪制normal 文字
    }

  • 三 onTouch Event
    case DOWN:
    case MOVE:
    int y=getY();//獲取現(xiàn)在手指在屏幕的Y坐標(biāo)砸彬。
    currentLetterPosition=(y+itemHeight/2)/itemHeight;//獲得字母的坐標(biāo)
    //回調(diào)接口傳到actvity
    onletterTouchListener.onLetterTouch(letterArray[currentLetterPosition])
    break;

  • 四回調(diào)方法
    private OnletterTouchListener onletterTouchListener;
    Inerface OnLetterTouchListener{
    onLetterTouch(CharSequence letter)
    }
    public void setOnLetterTouchListener(OnletterTouchListener Listener){
    this. onletterTouchListener=listener;
    }

  • 以上是大致的流程和思路塘偎,以下是源碼
    ...
    public class LetterBar extends View {
    /**

    • normal letter paint,focus paint
      /
      private Paint mPaint,focusPaint;
      /
      *
    • each letter height
      /
      private float itemHeight;
      /
      *
    • current y position,default is 0f
      */
      private int mCurrentY=0;
      private final String[] lettersArray = {"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", "#"};

    public LetterBar(Context context) {
    this(context,null);
    }

    public LetterBar(Context context, @Nullable AttributeSet attrs) {
    this(context, attrs,0);
    }

    public LetterBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    mPaint=new Paint();
    mPaint.setDither(true);
    mPaint.setAntiAlias(true);
    mPaint.setTextSize(sp2px(20));
    focusPaint=new Paint();
    focusPaint.setDither(true);
    focusPaint.setAntiAlias(true);
    focusPaint.setTextSize(sp2px(20));
    focusPaint.setColor(Color.RED);
    }

    private float sp2px(int sp) {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,sp,getResources().getDisplayMetrics());
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

       float textWidth=mPaint.measureText("W");
       int widthSize= (int) (textWidth+getPaddingLeft()+getPaddingRight());
       int heightSize=MeasureSpec.getSize(heightMeasureSpec)-getPaddingTop()-getPaddingBottom();
    
       setMeasuredDimension(widthSize,heightSize);
    

    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

      itemHeight=(getHeight()-getPaddingBottom()-getPaddingTop())/lettersArray.length;
      Paint.FontMetrics metrics = mPaint.getFontMetrics();
      float dy=(metrics.descent-metrics.ascent)/2-metrics.descent;
      float basey=itemHeight/2+dy;
      int itemWidth=0;
      int itemLetterY=0;
      for(int i=0;i<lettersArray.length-1;i++){
          itemWidth= (int) (mPaint.measureText(lettersArray[i]));
          itemLetterY= (int) (itemHeight*i+itemHeight/2+basey);
    
          if(mCurrentY==i) {
              Log.d("TAG","itemLetterY="+itemLetterY+" i="+i);
              canvas.drawText(lettersArray[i], getWidth() / 2 - itemWidth / 2, +itemLetterY, focusPaint);
          }
          else
              canvas.drawText(lettersArray[i],getWidth()/2-itemWidth/2,+itemLetterY,mPaint);
          }
    

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

      switch (event.getAction()){
          case MotionEvent.ACTION_DOWN:
          case MotionEvent.ACTION_MOVE:
    
          float letterY=(event.getY()-getPaddingTop()-itemHeight/2)/itemHeight;
          if(letterY==mCurrentY)
              return true;
          mCurrentY= (int) letterY;
          if(mCurrentY<0)
              mCurrentY=0;
          if(mCurrentY>lettersArray.length-1)
              mCurrentY=lettersArray.length-1;
    
          onLetterTouchListener.onLetterTouch(lettersArray[mCurrentY],true);
    
          invalidate();
          break;
          case MotionEvent.ACTION_UP:
          case MotionEvent.ACTION_CANCEL:
              if(mCurrentY<0)
                  mCurrentY=0;
              if(mCurrentY>lettersArray.length-1)
                  mCurrentY=lettersArray.length-1;
          synchronized (this) {
              postDelayed(new Runnable() {
                  @Override
                  public void run() {
                      onLetterTouchListener.onLetterTouch(lettersArray[mCurrentY], false);
                  }
              }, 1000);
    
    
              invalidate();
          }
          break;
      }
      Log.d("TAG","mCurrentY="+mCurrentY);
      return true;
    

    }
    private OnLetterTouchListener onLetterTouchListener;
    public interface OnLetterTouchListener{
    void onLetterTouch(CharSequence letter,boolean isTouch);
    }
    public void setOnLetterTouchListener(OnLetterTouchListener listener){
    this.onLetterTouchListener=listener;
    }
    }
    ...

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市拿霉,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌咱扣,老刑警劉巖绽淘,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異闹伪,居然都是意外死亡沪铭,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進店門偏瓤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來杀怠,“玉大人,你說我怎么就攤上這事厅克∨馔耍” “怎么了?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵证舟,是天一觀的道長硕旗。 經(jīng)常有香客問我,道長女责,這世上最難降的妖魔是什么漆枚? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮抵知,結(jié)果婚禮上墙基,老公的妹妹穿的比我還像新娘。我一直安慰自己刷喜,他們只是感情好残制,可當(dāng)我...
    茶點故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著吱肌,像睡著了一般痘拆。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上氮墨,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天纺蛆,我揣著相機與錄音吐葵,去河邊找鬼。 笑死桥氏,一個胖子當(dāng)著我的面吹牛温峭,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播字支,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼凤藏,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了堕伪?” 一聲冷哼從身側(cè)響起揖庄,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎欠雌,沒想到半個月后蹄梢,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡富俄,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年禁炒,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片霍比。...
    茶點故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡幕袱,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出悠瞬,到底是詐尸還是另有隱情们豌,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布阁危,位于F島的核電站玛痊,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏狂打。R本人自食惡果不足惜擂煞,卻給世界環(huán)境...
    茶點故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望趴乡。 院中可真熱鬧对省,春花似錦、人聲如沸晾捏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽惦辛。三九已至劳秋,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背玻淑。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工嗽冒, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人补履。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓添坊,卻偏偏與公主長得像,于是被迫代替她去往敵國和親箫锤。 傳聞我的和親對象是個殘疾皇子贬蛙,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,515評論 2 359

推薦閱讀更多精彩內(nèi)容