美文网首页
Android 自定义KeyboardView实现个别按键自定义

Android 自定义KeyboardView实现个别按键自定义

作者: 夏_Leon | 来源:发表于2018-05-29 20:11 被阅读0次

    系统KeyboardView无法实现对个别按键进行自定义背景色,需要重写一个KeyboardView才可以

    主要实现在于重写onDraw()方法,新建一个MyKeyboardView继承自KeyboardView

        @Override
        public void onDraw(Canvas canvas) {
            super.onDraw(canvas);
    
            Keyboard keyboard = getKeyboard();
            if (keyboard == null) return;
            List<Keyboard.Key> keys = keyboard.getKeys();
            if (keys != null && keys.size() > 0) {
                Paint paint = new Paint();
                paint.setTextAlign(Paint.Align.CENTER);
                Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
                paint.setTypeface(font);
                paint.setAntiAlias(true);
    
    
                //此处进行特殊按键的背景色处理
                for (Keyboard.Key key : keys) {
                    if (key.codes[0] == 34) {
    
                        //获取按键尺寸数据可优化
                        //绘制背景色
                        paint.setColor(getContext().getResources().getColor(R.color.gray_bfc3c7));
                        RectF rect=new RectF(key.x, key.y-Util.dip2px(BaseApplication.getAppContext(),2) + Util.dip2px(BaseApplication.getAppContext(),12),
                                key.x + key.width, key.y + key.height + Util.dip2px(BaseApplication.getAppContext(),10));
                        canvas.drawRoundRect(rect,Util.dip2px(BaseApplication.getAppContext(),4),Util.dip2px(BaseApplication.getAppContext(),4),paint);
    
                        //绘制icon
                        Drawable dr = getContext().getResources().getDrawable(R.drawable.key_board_cancel);
                        dr.setBounds(key.x+ Util.dip2px(BaseApplication.getAppContext(),8),
                                key.y + Util.dip2px(BaseApplication.getAppContext(),4+10),
                                key.x + key.width- Util.dip2px(BaseApplication.getAppContext(),8),
                                key.y + key.height - Util.dip2px(BaseApplication.getAppContext(),4-10));
                        dr.draw(canvas);
    
    
                    }
                }
            }
    
    
        }
    

    非常凌乱,仅供自己记录。

    相关文章

      网友评论

          本文标题:Android 自定义KeyboardView实现个别按键自定义

          本文链接:https://www.haomeiwen.com/subject/bpzajftx.html