Android 自定义数字键盘实现方法

自定义数字键盘

1.键盘布局
horizontalGap:按键间的水平间隔
keyHeight:按键高度以%或者%p结尾
keyWidth:按键宽度,”33.33333%p”
verticalGap:按键间的垂直间隔
codes:可以是系统给的固定值也可以是自定义的值

  <?xml version="1.0" encoding="utf-8"?>
 <Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:horizontalGap="1dp"
android:keyHeight="8%p"
android:keyWidth="33.33333%p"
android:verticalGap="1dp">
<Row>
    <Key
        android:codes="49"
        android:keyLabel="1"></Key>
    <Key
        android:codes="50"
        android:keyLabel="2"></Key>
    <Key
        android:codes="51"
        android:keyLabel="3"></Key>
</Row>
<Row>
    <Key
        android:codes="52"
        android:keyLabel="4"></Key>
    <Key
        android:codes="53"
        android:keyLabel="5"></Key>
    <Key
        android:codes="54"
        android:keyLabel="6"></Key>
</Row>
<Row>
    <Key
        android:codes="53"
        android:keyLabel="7"></Key>
    <Key
        android:codes="54"
        android:keyLabel="8"></Key>
    <Key
        android:codes="55"
        android:keyLabel="9"></Key>
</Row>
<Row>
    <Key
        android:codes="-10"
        android:keyLabel=""></Key>
    <Key
        android:codes="48"
        android:keyLabel="0"></Key>
    <Key
        android:codes="-5"
        android:keyIcon="@color/colorPrimary"></Key>
</Row>
</Keyboard>

2.继承keyboardview
这里主要就是3个点:1、获取按键布局(setkeyboard)2、绘制空白键跟删除键(onDraw)3、设置回调(OnKeyPressListener)。
删除按钮我做了一点处理,因为直接使用获取的dp(intrinsicWidth)的话图片会比较大,不是很好看,为了协调一点我宽高各自除了个6,然后计算了上下左右的边距(widthInterval,heightInterval),再进行的绘制。

这里用了自定义的属性展示在这里:

  <declare-styleable name="NumKeyView">
    <attr name="gbColor" format="color|reference"></attr>
    <attr name="deleteDrawable" format="reference"></attr>
</declare-styleable>

NumKeyView的代码

 public class NumKeyView extends KeyboardView implements OnKeyboardActionListener {
  //用于区分左下角空白按键,(要与xml里设置的数值相同)
  private int KEYCODE_EMPTY=-10;
   //删除按键背景图片
  private Drawable mDeleteDrawable;
  //最下面两个灰色的按键(空白按键跟删除按键)
  private int mBgColor;


 public NumKeyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context,attrs,0);
 }

 public NumKeyView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context, attrs, defStyleAttr);
 }

 private void init(Context context, AttributeSet attrs, int defStyleAttr) {
    TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.NumKeyView);
    mBgColor=ta.getColor(R.styleable.NumKeyView_gbColor, Color.RED);
    mDeleteDrawable=ta.getDrawable(R.styleable.NumKeyView_deleteDrawable);
    ta.recycle();
    //获取xml中的按键布局
    Keyboard keyboard=new Keyboard(context,R.xml.numkeyview);
    setKeyboard(keyboard);
    setEnabled(true);
    setPreviewEnabled(false);
    setOnKeyboardActionListener(this);
    }

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    List<Keyboard.Key> keys=getKeyboard().getKeys();
    for (Keyboard.Key key:keys){
        //绘制空白键
        if (key.codes[0]==KEYCODE_EMPTY){
            drawKeyBackGround(key,canvas);
        }else if (key.codes[0]==Keyboard.KEYCODE_DELETE){
            //绘制删除键背景
            drawKeyBackGround(key,canvas);
            //绘制按键图片
            drawkeyDelete(key,canvas);
        }
    }
}
private void drawKeyBackGround(Keyboard.Key key, Canvas canvas) {
    ColorDrawable colordrawable=new ColorDrawable(mBgColor);
    colordrawable.setBounds(key.x,key.y,key.x+key.width,key.y+key.height);
    colordrawable.draw(canvas);
}
private void drawkeyDelete(Keyboard.Key key, Canvas canvas) {
    int intrinsicWidth=mDeleteDrawable.getIntrinsicWidth();
    int intrinsicHeight=mDeleteDrawable.getIntrinsicHeight();
    int drawWidth=key.width;
    int drawHeight=key.height;
    if(drawWidth<intrinsicWidth){
        drawHeight=drawWidth*intrinsicHeight/intrinsicWidth;
    }
    drawWidth=drawWidth/6;
    drawHeight=drawHeight/6;
    int widthInterval=(key.width-drawWidth)/2;
    int heightInterval=(key.height-drawHeight)/2;

    mDeleteDrawable.setBounds(key.x+widthInterval,key.y+heightInterval,key.x+widthInterval+drawWidth,key.y+heightInterval+drawHeight);
    mDeleteDrawable.draw(canvas);
}
//回调接口
public interface OnKeyPressListener{
    //添加数据回调
    void onInertKey(String text);
    //删除数据回调
    void onDeleteKey();
}
private OnKeyPressListener mOnkeyPressListener;
public void setOnKeyPressListener(OnKeyPressListener li){
    mOnkeyPressListener=li;
}
@Override
public void onKey(int i, int[] ints) {
        if (i==Keyboard.KEYCODE_DELETE&&mOnkeyPressListener!=null){
            //添加数据回调
            mOnkeyPressListener.onDeleteKey();
        }else if (i!=KEYCODE_EMPTY){
            //删除数据回调
            mOnkeyPressListener.onInertKey(Character.toString((char) i));
        }
}
@Override
public void onPress(int i) {

}

@Override
public void onRelease(int i) {

}



@Override
public void onText(CharSequence charSequence) {

}

@Override
public void swipeRight() {
    super.swipeRight();
}

@Override
public void swipeDown() {
    super.swipeDown();
}

@Override
public void swipeLeft() {
    super.swipeLeft();
}

@Override
public void swipeUp() {
    super.swipeUp();
}
}

注意!调用的时候,因为使用了自定义属性(AS)所以注意添加下面一行代码
xmlns:app="http://schemas.android.com/apk/res-auto"
3.其他部分
上面按键部分就做好了,下面看下自定义按键的中上面的接口回调

public class KeyDemo extends AppCompatActivity {
private EditText mEditText;
private NumKeyView mKeyView;
private Button mButton;
private LinearLayout mLinearlayout;
private PopupWindow mPop;
private LinearLayout mProgressBarLn;
private View mPopView;
private Handler mhandler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        mPop.dismiss();
        mKeyView.setVisibility(View.VISIBLE);
        mProgressBarLn.setVisibility(View.INVISIBLE);
        mButton.setText("完成");
    }
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_keyboard);
    init();
    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //点击按钮显示键盘
            mPop.showAtLocation(mLinearlayout, Gravity.BOTTOM,0,0);
        }
    });
    //设置回调,并进行文本的插入与删除
    mKeyView.setOnKeyPressListener(new NumKeyView.OnKeyPressListener() {
        @Override
        public void onInertKey(String text) {
            if(mEditText.getText().length()<6){
                mEditText.append(text);
                //文本长度为6时隐藏键盘,显示进度条,一段时间后pop消失
                if (mEditText.getText().length()==6){
                    mKeyView.setVisibility(View.INVISIBLE);
                    mProgressBarLn.setVisibility(View.VISIBLE);
                    mhandler.sendEmptyMessageDelayed(0x11,4000);
                }
            }
        }

        @Override
        public void onDeleteKey() {
            int last=mEditText.getText().length();
            if (last>0){
                //删除最后一位
            mEditText.getText().delete(last-1,last);
            }
        }
    });

}

private void init() {
    mEditText= (EditText) findViewById(R.id.et);
    mButton= (Button) findViewById(R.id.bt);
    mLinearlayout= (LinearLayout) findViewById(R.id.ln);
    mPop=new PopupWindow();
    mPopView=LayoutInflater.from(getApplicationContext()).inflate(R.layout.keyboard_pop,null);
    mPop.setContentView(mPopView);
    mPop.setTouchable(true);
    mPop.setFocusable(true);
    mPop.setBackgroundDrawable(new ColorDrawable());
    mPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
    mPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    mPop.setAnimationStyle(R.style.PopWindowstyle);
    mProgressBarLn= (LinearLayout) mPopView.findViewById(R.id.progressbar_ln);
    mKeyView= (NumKeyView) mPopView.findViewById(R.id.keyboardview);
}
}

主布局

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/ln"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
    android:id="@+id/et"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<Button
    android:id="@+id/bt"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="点击弹出弹出窗"/>

</LinearLayout>

Pop布局

 <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<com.zhjh.keydemo.NumKeyView
    android:id="@+id/keyboardview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:keyBackground="@color/colorAccent"
    app:gbColor="#eeeeee"
    app:deleteDrawable="@drawable/keyboard_backspace"
    />
<LinearLayout
    android:id="@+id/progressbar_ln"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="invisible"
    >
    <View
        android:layout_width="match_parent"
        android:layout_height="2px"
        android:background="#000000"
        ></View>
    <ProgressBar
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="20dp"
        style="@android:style/Widget.Holo.ProgressBar.Large"
        />
</LinearLayout>

</FrameLayout>

Pop动画

弹出

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:fromXDelta="0"
    android:fromYDelta="100%"
    android:toXDelta="0"
    android:toYDelta="0"
    android:duration="1000"
    ></translate>

 </set>

消失

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
 android:toXDelta="0"
android:fromXDelta="0"
android:fromYDelta="0"
android:toYDelta="100%"
android:duration="1000"
></translate>
</set>

定义动画

  <style name="PopWindowstyle">
   <item name="android:windowEnterAnimation">@anim/showanim</item>
   <item name="android:windowExitAnimation">@anim/dismissanim</item>
 </style>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,050评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,943评论 4 60
  • 今日开心播种,他日定有收成!无比感恩实修群老师和同学的带领、督导和激励!每晚都无比喜悦地为自己播种的好种子浇水施肥...
    如意宝阅读 231评论 0 2
  • 昨夜星辰昨夜风 画楼西畔桂堂东 时光流逝 岁月如梭 螺旋之光时光的旅程 波浪长发岁月的感知 女神在演奏唯美夜曲 巴...
    lynls8888阅读 242评论 1 0
  • 班上频繁的琐碎和生活的日常,每天一样,但也可以不一样。 自从开始了100天写作的练习,来自各方的反应,令生活不一样...
    悦书_王小悦阅读 192评论 3 5