安卓实战:自定义软键盘
程序开发
2023-09-07 17:26:50
安卓实战:自定义软键盘
(注:安卓实战项目记账本的一部分内容)
在记账本中需要输入数字,萌生了想自己制作一个数字软键盘的内容,失败过程不眷数,直接展示最终成果
首先是页面布局:
key.xml
//键盘与键盘间垂直方向分割 //数字键1 //数字键2 //数字键3 //删除键|
//数字键4 //数字键5 //数字键6 //确定键,设置较大|
//数字键7 //数字键8 //数字键9|
//清零键 //0键 //.键
然后是逻辑编写:
KeyboardUtils.java
package com.example.mytally.utils;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.example.mytally.R;public class KeyBoardUtils {private final Keyboard k1; //自定义键盘private KeyboardView keyboardView;private EditText editText; //设置一个变量EditText使得输入处随软键盘输入变化 //生成两者的构造方法public interface OnEnsureListener{public 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() {@Overridepublic void onPress(int primaryCode) {}@Overridepublic void onRelease(int primaryCode) {}@Overridepublic void onKey(int primaryCode, int[] keyCodes) {Editable editable = editText.getText();int start = editText.getSelectionStart();switch (primaryCode) {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)primaryCode));break;}}@Overridepublic void onText(CharSequence text) {}@Overridepublic void swipeLeft() {}@Overridepublic void swipeRight() {}@Overridepublic void swipeDown() {}@Overridepublic 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);}}
}
成果图:
有关于这个的问题可以随时找我交流
原文链接
作者:黄书竞
标签:
上一篇:
前端——JS中获取时间以及格式化处理
下一篇:
相关文章
-
无相关信息