Android自定义软键盘样式:字母、数字、标点三种切换

先看效果图:

Android自定义软键盘样式:字母、数字、标点三种切换_第1张图片

Android自定义软键盘样式:字母、数字、标点三种切换_第2张图片

Android自定义软键盘样式:字母、数字、标点三种切换_第3张图片

1.在需要的调用软键盘的activity_mian.xml中加入键盘控件

 




    
1.1
 
android:keyPreviewLayout="@layout/key_preview_layout"这个是长按键盘时弹出框的样式,如果不写,系统默认,默认的有时会会看不清
key_preview_layout.xml:
 

1.2
android:keyBackground="@drawable/btn_keyboard_key"按键的形状
 
btn_keyboard_key.xml:
 


    
    

 

 

2.然后在res文件夹下新建文件夹,里面新建三个文件,即每种键盘样式的布局分别为qwerty.xml, symbols.xml, punctuate.xml

 

字母键盘-qwerty.xml:

 



   
      
      
      
      
      
      
      
      
      
      
   
   
      
      
      
      
      
      
      
      
      
   
   
      
      
      
      
      
      
      
      
      
   
   
      
      
      
      
      
   

数字键盘-symbols.xml:

 

 

 

 




   
      
      
      
      
      
      
      
      
      
      
   
   
      
      
      
      
      
      
      
      
      
      
   
   
      
      
      
      
      
      
      
      
   
   
      
      
      
   

标点键盘-punctuate.xml

 

 




    
        
        
        
        
        
        
        
        
        
    
    
        
        
        
        
        
        
        
        
        
    
    
        
        
        
        
        
        
        
        
    
    
        
        
        
    

android:keyIcon="@drawable/space" 的部分没有图片的话可以换成 android:keyLabel=" "括号里用相应字母或符号代替

 

 

3.然后就是KeyBoardUtil工具类,网上有很多内容大同小异,我为了实现三种键盘的切换进行了一些改动

 

 

KeyBoardUtil.java

 

package com.dcdz.app.base;

import android.app.Activity;
import android.content.Context;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.Keyboard.Key;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;

import com.dcdz.app.R;

import java.util.List;

public class KeyboardUtil {
    private Context ctx;
    private Activity act;
    private KeyboardView keyboardView;
    private Keyboard k1;// 字母键盘
    private Keyboard k2;// 数字键盘
    private Keyboard k3;//标点符号键盘
    public boolean isnun = false;// 是否数据键盘
    public boolean ispun = false;//是否标点键盘
    public boolean isupper = false;// 是否大写

    public static final int KEYCODE_PUN = -7;

    private EditText ed;

    public KeyboardUtil(Activity act, Context ctx, EditText edit) {
        this.act = act;
        this.ctx = ctx;
        this.ed = edit;
        k1 = new Keyboard(ctx, R.xml.qwerty);
        k2 = new Keyboard(ctx, R.xml.symbols);
        k3 = new Keyboard(ctx,R.xml.punctuate);
        keyboardView = (KeyboardView) act.findViewById(R.id.keyboard_view);
        keyboardView.setKeyboard(k1);
        keyboardView.setEnabled(true);
        keyboardView.setPreviewEnabled(true);
        keyboardView.setOnKeyboardActionListener(listener);
}

    private OnKeyboardActionListener listener = 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) {
            Editable editable = ed.getText();
            int start = ed.getSelectionStart();
            if (primaryCode == Keyboard.KEYCODE_CANCEL) {// 完成
                hideKeyboard();
            } else if (primaryCode == Keyboard.KEYCODE_DELETE) {// 回退
                if (editable != null && editable.length() > 0) {
                    if (start > 0) {
                        editable.delete(start - 1, start);
                    }
                }
            } else if (primaryCode == Keyboard.KEYCODE_SHIFT) {// 大小写切换
                changeKey();
                keyboardView.setKeyboard(k1);


            } else if (primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {// 数字键盘切换
                if (isnun) {
                    isnun = false;
                    keyboardView.setKeyboard(k1);
                } else {
                    isnun = true;
                    keyboardView.setKeyboard(k2);
                }
            }else if(primaryCode == KEYCODE_PUN){
                if(ispun){
                    ispun = false;
                    keyboardView.setKeyboard(k2);
                }else {
                    ispun = true;
                    keyboardView.setKeyboard(k3);
                }
            }
            else if (primaryCode == 57419) { // go left
                if (start > 0) {
                    ed.setSelection(start - 1);
                }
            } else if (primaryCode == 57421) { // go right
                if (start < ed.length()) {
                    ed.setSelection(start + 1);
                }
            } else {
                editable.insert(start, Character.toString((char) primaryCode));
            }
        }
    };

    /**
     * 键盘大小写切换
     */
    private void changeKey() {
        List keylist = k1.getKeys();
        if (isupper) {//大写切换小写
            isupper = false;
            for(Key key:keylist){
                if (key.label!=null && isword(key.label.toString())) {
                    key.label = key.label.toString().toLowerCase();
                    key.codes[0] = key.codes[0]+32;
                }
            }
        } else {//小写切换大写
            isupper = true;
            for(Key key:keylist){
                if (key.label!=null && isword(key.label.toString())) {
                    key.label = key.label.toString().toUpperCase();
                    key.codes[0] = key.codes[0]-32;
                }
            }
        }
    }

    public void showKeyboard() {
        int visibility = keyboardView.getVisibility();
        if (visibility == View.GONE || visibility == View.INVISIBLE) {
            keyboardView.setVisibility(View.VISIBLE);
        }
    }

    public void hideKeyboard() {
        int visibility = keyboardView.getVisibility();
        if (visibility == View.VISIBLE) {
            keyboardView.setVisibility(View.INVISIBLE);
        }
    }

    private boolean isword(String str){
        String wordstr = "abcdefghijklmnopqrstuvwxyz";
        if (wordstr.indexOf(str.toLowerCase())>-1) {
            return true;
        }
        return false;
    }


}

 

 

4.最后是调用

 

4.1在Fragment里调

一般的项目都是在Fragment里调的,这个根据你的文本框的位置具体来定吧

我这边内容较多,只写关键代码

 

public class UserLoginFragment extends SupportFragment {
    FragmentFingerUserloginBinding binding;
    private EditText etUserName;
    private EditText etPassword;
 
    private Context ctx;
    private Activity act;
    private KeyboardView keyboardView;
  
   
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_finger_userlogin, container, false);

        act = getActivity();
        ctx = getActivity().getBaseContext();
        keyboardView = (KeyboardView) getActivity().findViewById(R.id.keyboard_view);
       
        etUserName = binding.etUsername;
        etPassword = binding.etPassword;

        initView();
        return binding.getRoot();
    }

    private void initView() {
        if (binding != null) {
            etUserName.requestFocus();
//            etUserName.setFocusableInTouchMode(true);
            etUserName.addTextChangedListener(watcher);
            etPassword.addTextChangedListener(watcher);

            etUserName.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
            etPassword.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);

            //调用自定义键盘
            etUserName.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    keyboardView.setKeyboard(k1);
//                    int inputback = etUserName.getInputType();
//                    etUserName.setInputType(InputType.TYPE_NULL);
                    new KeyboardUtil(act,act.getBaseContext(), etUserName).showKeyboard();
//                    etUserName.setInputType(inputback);
                    return false;
                }
            });
            etPassword.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    keyboardView.setKeyboard(k2);
                    new KeyboardUtil(act, act.getBaseContext(), etPassword).showKeyboard();
                    return false;
                }
            });
        }

    }

}

 

 

 

 

 

4.2在Activity里调,在Activity里调我是为了在这里实现触摸屏幕其他位置隐藏软键盘

 

关键代码

 

public class FingerActivity extends SupportActivity {
    private KeyboardView keyboardView;

    @SuppressLint("ResourceType")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_finger);

        keyboardView = (KeyboardView) findViewById(R.id.keyboard_view);

        initView();
        loadRootFragment(new UserLoginFragment());
    }
 
public boolean onTouchEvent(MotionEvent event) {
        if(null != this.getCurrentFocus()){
            /**
             * 点击空白位置 隐藏软键盘
             */
            keyboardView.setVisibility(View.INVISIBLE);
        }
        return super .onTouchEvent(event);
    }

5到这里即基本可以实现了,在使用的时候肯定还会遇到很多小问题,这里也不一 一列举了。

 

 

 
 

 

 

 

 

 

 

 
 

 

 

 

你可能感兴趣的:(Android自定义软键盘样式:字母、数字、标点三种切换)