新建util包,新建keyboardutils的java类,当然在之前我们已经在项目中导入了google的material的jar包了。
package com.open.tally.util;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.text.Editable;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import com.open.tally.R;
public class KeyBoardUtils {
private final Keyboard k1;//自定义键盘
private KeyboardView keyboardView;
private EditText editText;
public interface OnEnsureListener{
public static void onEnsure(){
}
}
OnEnsureListener onEnsureListener;
public void setOnEnsureListener(OnEnsureListener onEnsureListener) {
this.onEnsureListener = onEnsureListener;
}
public KeyBoardUtils(KeyboardView keyboardView, EditText editText) {
this.keyboardView = keyboardView;
this.editText = editText;
this.editText.setInputType(InputType.TYPE_NULL);//取消弹出系统键盘
k1 = new Keyboard(this.editText.getContext(), R.xml.key);
this.keyboardView.setKeyboard(k1);
this.keyboardView.setEnabled(true);
this.keyboardView.setPreviewEnabled(false);
this.keyboardView.setOnKeyboardActionListener(listener);
}
KeyboardView.OnKeyboardActionListener listener=new KeyboardView.OnKeyboardActionListener() {
@Override
public void onPress(int i) {
}
@Override
public void onRelease(int i) {
}
@Override
public void onKey(int i, int[] ints) {
Editable editable=editText.getText();
int start= editText.getSelectionStart();
switch (i){
case Keyboard.KEYCODE_DELETE://用户点击删除键
if (editable!=null&&editable.length()>0){
if(start>0){
editable.delete(start-1,start);
}
}
break;
case Keyboard.KEYCODE_CANCEL://用户典籍取消键
editable.clear();
break;
case Keyboard.KEYCODE_DONE://用户点击确定键
OnEnsureListener.onEnsure();//通过接口回调的方法,当点击确定后,可以调用这个方法
break;
default://用户点击其他键,直接插入
editable.insert(start,Character.toString((char) i));
break;
}
}
@Override
public void onText(CharSequence charSequence) {
}
@Override
public void swipeLeft() {
}
@Override
public void swipeRight() {
}
@Override
public void swipeDown() {
}
@Override
public void swipeUp() {
}
};
//显示键盘
public void showKeyBoard(){
int visibility = keyboardView.getVisibility();
if (visibility== View.INVISIBLE||visibility==View.GONE){
keyboardView.setVisibility(View.VISIBLE);
}
}
//隐藏键盘
public void hideKeyBoard(){
int visibility = keyboardView.getVisibility();
if(visibility==View.VISIBLE||visibility==View.INVISIBLE){
keyboardView.setVisibility(View.GONE);
}
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章