AndroidKeyboard(自定義輸入法)

凌浩雨發表於2017-10-18
  1. Keyboard的xml檔案配置
<?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:keyWidth="66%p"
      android:keyIcon="@mipmap/icon_number_del" />
  </Row>

</Keyboard>
  1. 軟鍵盤的佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
  <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/bg_keyboard_btn"
      android:keyTextColor="@android:color/primary_text_light"
      android:keyTextSize="32sp"
      android:visibility="visible"
      />
</LinearLayout>
  1. 自定義軟鍵盤工具類
package com.mazaiting;

import android.annotation.TargetApi;
import android.app.Activity;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
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 com.mazaiting.keyboardviwe.R;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 自定義軟鍵盤
 * Created by mazaiting on 2017/10/18.
 */

public class KeyBoardUtil {
  /**
   * 顯示鍵盤的檢視
   */
  private Activity mActivity;
  /**
   * 鍵盤檢視
   */
  private KeyboardView mKeyboardView;
  /**
   * 鍵盤
   */
  private Keyboard mKeyboard;
  /**
   * 輸入框
   */
  private EditText mEditText;
  /**
   * 鍵盤佈局
   */
  private View mViewContainer;

  /**
   * 焦點改變監聽
   */
  View.OnFocusChangeListener mOnFocusChangeListener = new View.OnFocusChangeListener() {
    @Override public void onFocusChange(View view, boolean hasFocus) {
      if (hasFocus) showSoftKeyboard();
      else hideSoftKeyboard();
    }
  };
  /**
   * 構造方法
   * @param activity 根檢視
   */
  public KeyBoardUtil(Activity activity){
    this.mActivity = activity;
    this.mKeyboard = new Keyboard(mActivity, R.xml.keyboard_view);
  }

  /**
   * 繫結輸入框
   * @param editText 輸入框
   * @param isAuto 是否自動顯示
   */
  public void attachTo(EditText editText, boolean isAuto){
    this.mEditText = editText;
    hideSystemSoftKeyboard(this.mEditText);
    setAutoShowOnFocus(isAuto);
  }

  /**
   * 隱藏系統軟體盤
   * @param editText 輸入框
   */
  @TargetApi(Build.VERSION_CODES.KITKAT) private void hideSystemSoftKeyboard(EditText editText) {
    int sdkInt = Build.VERSION.SDK_INT;
    if (sdkInt < 11){
      editText.setInputType(InputType.TYPE_NULL);
    } else {
      try {
        Class<EditText> cls = EditText.class;
        Method setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
        setShowSoftInputOnFocus.setAccessible(true);
        setShowSoftInputOnFocus.invoke(editText, false);
      } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * 焦點時自動顯示
   * @param enabled 是否顯示
   */
  private void setAutoShowOnFocus(boolean enabled){
    if (null == mEditText) return;
    if (enabled) mEditText.setOnFocusChangeListener(mOnFocusChangeListener);
    else mEditText.setOnFocusChangeListener(null);
  }

  /**
   * 顯示軟鍵盤
   */
  public void showSoftKeyboard() {
    if (null == mViewContainer) {
      mViewContainer = mActivity.getLayoutInflater().inflate(R.layout.layout_view, null);
    } else {
      if (null != mViewContainer.getParent()) return;
    }

    FrameLayout frameLayout = (FrameLayout) mActivity.getWindow().getDecorView();
    KeyboardView keyboardView = mViewContainer.findViewById(R.id.keyboard_view);
    this.mKeyboardView = keyboardView;
    this.mKeyboardView.setKeyboard(mKeyboard);
    this.mKeyboardView.setEnabled(true);
    this.mKeyboardView.setPreviewEnabled(false);
    this.mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener);

    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
        FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.gravity = Gravity.BOTTOM;
    frameLayout.addView(mViewContainer, layoutParams);
    mViewContainer.setAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.anim_down_to_up));
  }

  /**
   * 隱藏軟鍵盤
   */
  public void hideSoftKeyboard() {
    if (null != mViewContainer && null != mViewContainer.getParent()){
      mViewContainer.setAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.anim_up_to_down));
      ((ViewGroup)mViewContainer.getParent()).removeView(mViewContainer);
    }
  }

  /**
   * 判斷是否顯示
   * @return true, 顯示; false, 不顯示
   */
  public boolean isShowing(){
    if (null == mViewContainer) return false;
    return mViewContainer.getVisibility() == View.VISIBLE;
  }

  KeyboardView.OnKeyboardActionListener mOnKeyboardActionListener = new KeyboardView.OnKeyboardActionListener() {
    @Override public void onPress(int i) {}
    @Override public void onRelease(int i) {}

    @Override public void onKey(int primaryCode, int[] keyCodes) {
      if (null != mEditText) keyCode(primaryCode, mEditText);
      mKeyboardView.postInvalidate();
    }

    @Override public void onText(CharSequence charSequence) {}
    @Override public void swipeLeft() {}
    @Override public void swipeRight() {}
    @Override public void swipeDown() {}
    @Override public void swipeUp() {}
  };

  /**
   * 字元
   * @param primaryCode 主要字元
   * @param editText 編輯框
   */
  private void keyCode(int primaryCode, EditText editText) {
    Editable editable = editText.getText();
    int start = editText.getSelectionStart();
    if (primaryCode == Keyboard.KEYCODE_DELETE) { // 回退
      if (editText.hasFocus()) {
        if (!TextUtils.isEmpty(editable)){
          if (start > 0) editable.delete(start - 1, start);
        }
      }
    } else if (primaryCode == Keyboard.KEYCODE_SHIFT) { // 大小寫切換
      mKeyboardView.setKeyboard(mKeyboard);
    } else {
      if (editText.hasFocus()) editable.insert(start, Character.toString((char) primaryCode));
    }
  }
}
  1. 使用
package com.mazaiting.keyboardview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.mazaiting.KeyBoardUtil;

public class MainActivity extends AppCompatActivity {
  private EditText editText;
  private KeyBoardUtil mKeyBoardUtil;
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editText = (EditText) this.findViewById(R.id.editText);
    mKeyBoardUtil = new KeyBoardUtil(this);
    mKeyBoardUtil.attachTo(editText, true);
  }

  /**顯示*/
  public void show(View view){
    mKeyBoardUtil.showSoftKeyboard();
  }
  /**隱藏*/
  public void hide(View view){
    mKeyBoardUtil.hideSoftKeyboard();
  }
}


相關文章