Android开发(45) 自定义软键盘

概述

在项目开发中遇到一个需求,”只要数字键盘的输入,仅仅有大写字母的输入,某些输入法总是会提示更新,弹出广告等“,使得我们需要自定义输入。

关联知识

  • KeyboardView 一个视图对象,展示了键盘。它需要关联到一个 Keyboard对象才能展示。
  • Keyboard 键盘对象,通过加载xml的配置获得键盘的排列。
  • xml 文件键盘描述 一个xml文件,放置在 xml 资源文件夹下,描述了 显示的键盘按钮,和排列,键盘宽度和高度等。

具体实现

准备xml键盘描述文件

在xml文件夹下创建文件,下面的代码中使用 “ 33%p” 这样的单位指定一定的 百分比,以适配屏幕,详细内容如下:

<?xml version="1.0" encoding="UTF-8"?><!-- 数字键盘 -->
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:horizontalGap="0dp"
    android:keyHeight="61dp"
    android:keyWidth="33%p"
    android:verticalGap="0dp">
    <Row>
        <Key
            android:codes="49"
            android:keyEdgeFlags="left"
            android:keyLabel="1" />
        <Key
            android:codes="50"
            android:keyLabel="2" />
        <Key
            android:codes="51"
            android:keyLabel="3" />
    </Row>
    <Row>
        <Key
            android:codes="52"
            android:keyEdgeFlags="left"
            android:keyLabel="4" />
        <Key
            android:codes="53"
            android:keyLabel="5" />
        <Key
            android:codes="54"
            android:keyLabel="6" />
    </Row>
    <Row>
        <Key
            android:codes="55"
            android:keyEdgeFlags="left"
            android:keyLabel="7" />
        <Key
            android:codes="56"
            android:keyLabel="8" />
        <Key
            android:codes="57"
            android:keyLabel="9" />
    </Row>
    <Row>
        <Key
            android:codes="48"
            android:keyEdgeFlags="left"
            android:keyLabel="0" />
        <Key
            android:codes="-5"
            android:isRepeatable="true"
            android:keyIcon="@drawable/keyboard_delete"
            android:keyWidth="66%p" />
    </Row>
</Keyboard>

创建Keyboard对象

要先配置好xml文件,在构造方法里传入上面的xml文件

    this.keyboard = new Keyboard(mActivity, R.xml.small_keyboard);

构造KeyboardView

keyboardView 对象可以在 xml 中描述,类似下面这样

<android.inputmethodservice.KeyboardView
        android:id="@+id/keyboard_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@android:color/transparent"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:keyBackground="@drawable/keyboard_key"
        android:keyTextColor="@color/white"
        android:keyTextSize="@dimen/sp_32"
        android:visibility="visible" />

获得 KeyboardView并进行配置,需要关联到具体的 keyboard 对象

    KeyboardView keyboardView = (KeyboardView) viewContainer.findViewById(R.id.keyboard_view);
    this.keyboardView = keyboardView;
    this.keyboardView.setKeyboard(keyboard);
    this.keyboardView.setEnabled(true);
    this.keyboardView.setPreviewEnabled(false);
    this.keyboardView.setOnKeyboardActionListener(listener2);

隐藏系统自带的键盘

根据android系统的版本的不同,有不同的方法,需要利用反射,见代码:

 /**
     * 隐藏系统键盘
     *
     * @param editText
     */
    public static void hideSystemSofeKeyboard(EditText editText) {
        int sdkInt = Build.VERSION.SDK_INT;
        if (sdkInt >= 11) {
            try {
                Class<EditText> cls = EditText.class;
                Method setShowSoftInputOnFocus;
                setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(editText, false);

            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            editText.setInputType(InputType.TYPE_NULL);
        }
    }

从底部弹出键盘

输入法需要从页面底部向上弹出,需要一个过渡动画,android每个页面都有一个window,window包含了一个getDecorView 根视图,我们要把键盘的视图添加到这个根视图下,配合动画出现键盘。

public void showSoftKeyboard() {

    if (viewContainer == null) {
        viewContainer = mActivity.getLayoutInflater().inflate(R.layout.keyboardview_layout, null);
    } else {
        if (viewContainer.getParent() != null)
            return;
    }

    FrameLayout frameLayout = (FrameLayout) mActivity.getWindow().getDecorView();
    KeyboardView keyboardView = (KeyboardView) viewContainer.findViewById(R.id.keyboard_view);
    this.keyboardView = keyboardView;
    this.keyboardView.setKeyboard(keyboard);
    this.keyboardView.setEnabled(true);
    this.keyboardView.setPreviewEnabled(false);
    this.keyboardView.setOnKeyboardActionListener(listener2);

    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
    lp.gravity = Gravity.BOTTOM;
    frameLayout.addView(viewContainer, lp);
    //viewContainer.setVisibility(View.GONE);
    viewContainer.setAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.down_to_up));
}

完整的代码:

package vir56k.democustomkeyboard;

import android.app.Activity;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.os.Build;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.FrameLayout;

import java.lang.reflect.Method;

public class PopupKeyboardUtil {
    private Activity mActivity;

    private KeyboardView keyboardView;
    private Keyboard keyboard;// 全键盘包括数字和字母

    private EditText editText1;

    public PopupKeyboardUtil(Activity mActivity) {
        this.mActivity = mActivity;
        this.keyboard = new Keyboard(mActivity, R.xml.small_keyboard);
    }

    public void attachTo(EditText editText, boolean isAuto) {
        this.editText1 = editText;
        hideSystemSofeKeyboard(this.editText1);
        setAutoShowOnFocs(isAuto);
    }

    public void setAutoShowOnFocs(boolean enable) {
        if (editText1 == null)
            return;
        if (enable)
            editText1.setOnFocusChangeListener(onFocusChangeListener1);
        else
            editText1.setOnFocusChangeListener(null);
    }

    View.OnFocusChangeListener onFocusChangeListener1 = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus)
                showSoftKeyboard();
            else
                hideSoftKeyboard();
        }
    };

    View viewContainer;

    public void showSoftKeyboard() {

        if (viewContainer == null) {
            viewContainer = mActivity.getLayoutInflater().inflate(R.layout.keyboardview_layout, null);
        } else {
            if (viewContainer.getParent() != null)
                return;
        }

        FrameLayout frameLayout = (FrameLayout) mActivity.getWindow().getDecorView();
        KeyboardView keyboardView = (KeyboardView) viewContainer.findViewById(R.id.keyboard_view);
        this.keyboardView = keyboardView;
        this.keyboardView.setKeyboard(keyboard);
        this.keyboardView.setEnabled(true);
        this.keyboardView.setPreviewEnabled(false);
        this.keyboardView.setOnKeyboardActionListener(listener2);

        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        lp.gravity = Gravity.BOTTOM;
        frameLayout.addView(viewContainer, lp);
        //viewContainer.setVisibility(View.GONE);
        viewContainer.setAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.down_to_up));
    }


    public void hideSoftKeyboard() {
        if (viewContainer != null && viewContainer.getParent() != null) {
            ((ViewGroup) viewContainer.getParent()).removeView(viewContainer);
        }
    }

    public boolean isShowing() {
        if (viewContainer == null)
            return false;
        return viewContainer.getVisibility() == View.VISIBLE;
    }

    /**
     * 隐藏系统键盘
     *
     * @param editText
     */
    public static void hideSystemSofeKeyboard(EditText editText) {
        int sdkInt = Build.VERSION.SDK_INT;
        if (sdkInt >= 11) {
            try {
                Class<EditText> cls = EditText.class;
                Method setShowSoftInputOnFocus;
                setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(editText, false);

            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            editText.setInputType(InputType.TYPE_NULL);
        }
    }

    private OnKeyboardActionListener listener2 = new OnKeyboardActionListener() {
        @Override
        public void swipeUp() {
        }

        @Override
        public void swipeRight() {
        }

        @Override
        public void swipeLeft() {
        }

        @Override
        public void swipeDown() {
        }

        @Override
        public void onText(CharSequence text) {
        }

        @Override
        public void onRelease(int primaryCode) {
        }

        @Override
        public void onPress(int primaryCode) {
        }

        @Override
        public void onKey(int primaryCode, int[] keyCodes) {
            if (editText1 != null) {
                keyCode_delect(primaryCode, editText1);
            }
            keyboardView.postInvalidate();
        }
    };

    /**
     * 判断回退键 和大小写切换
     *
     * @param primaryCode
     * @param edText
     */
    private void keyCode_delect(int primaryCode, EditText edText) {

        Editable editable = edText.getText();
        int start = edText.getSelectionStart();
        if (primaryCode == Keyboard.KEYCODE_DELETE) {// 回退
            if (edText.hasFocus()) {
                if (!TextUtils.isEmpty(editable)) {
                    if (start > 0) {
                        editable.delete(start - 1, start);
                    }
                }
            }

        } else if (primaryCode == Keyboard.KEYCODE_SHIFT) {// 大小写切换
            keyboardView.setKeyboard(keyboard);
        } else {
            if (edText.hasFocus()) {
                editable.insert(start, Character.toString((char) primaryCode));
            }
        }
    }

}

功能完成后,具体调用的演示:

package vir56k.democustomkeyboard;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;


public class MainActivity extends AppCompatActivity {
    EditText edittext1;
    PopupKeyboardUtil smallKeyboardUtil;
    private View viewContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edittext1 = (EditText) findViewById(R.id.edittext1);

        smallKeyboardUtil = new PopupKeyboardUtil(self());
        smallKeyboardUtil.attachTo(edittext1, false);
        //smallKeyboardUtil.setAutoShowOnFocs(false);
    }

    public void onClickView(View view) {
        if (view.getId() == R.id.btn1)
            smallKeyboardUtil.showSoftKeyboard();
        if (view.getId() == R.id.btn2)
            smallKeyboardUtil.hideSoftKeyboard();

    }

    private Activity self() {
        return this;
    }
}

代码下载:

https://github.com/vir56k/demo/tree/master/demo.customkeyboard

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,576评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,623评论 4 59
  • 学校体检。大妈面无表情地拉着皮尺给同学检查身体,一个两个三个。轮到我了,她先是测了臀部,又往上移到下肋骨一圈,然后...
    暂未定阅读 172评论 0 1
  • ➰ 格子小姐从小学就开始发胖,胖了很多年。但她始终拥有一颗软绵绵的少女...
    日日要加油阅读 274评论 2 2
  • 曾经看过最好的爱情故事是在中学语文书上读到的,归有光的《项脊轩志》中写道:庭有枇杷树,吾妻死时手植也。今已亭亭如盖...
    你好哇冬至阅读 1,528评论 4 10