Android基于KeyboardView和Keyboard实现自定义软键盘
在一些特别的情况下我们需要去自定义键盘
例如: 银行app的密码输入之类的
笨方法就是直接使用布局写我们的自定义软键盘
但这样写的话我们的代码量就很多
Android官方提供了KeyboardView和Keyboard两个类
我们可以用这两个类去实现自己的软键盘
Demo 已上传 GitHub
https://github.com/pengchengfuGit/DIYKeyboard.git
1.主界面的布局与代码
这是我们主界面的xml
android:layout_width="match_parent"
android:background="@android:color/darker_gray"
android:layout_height="match_parent">
android:layout_width="match_parent"
android:layout_height="50dp" />
android:background="@android:color/white"
android:layout_width="match_parent"
android:keyBackground="@android:color/holo_purple"
android:keyTextColor="#333333"
android:focusable="true"
android:focusableInTouchMode="true"
android:paddingTop="1dp"
android:shadowColor="#FFFFFF"
android:shadowRadius="0.0"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
RelativeLayout>
主界面的Activity 这里写了个KeyBoardUtil来初始的我们自定义软键盘
public class MainActivity extends Activity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
final KeyboardView keyboard = (KeyboardView) findViewById(R.id.kv_keyboard);
final EditText editText = (EditText) findViewById(R.id.et);
//在我们点EditText的时候弹出我们的软键盘
editText.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(editText.hasFocus()){
//用来初始化我们的软键盘
new KeyBoardU