How can you make a custom keyboard in Android?

前端 未结 9 2323
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 04:42

I want to make a custom keyboard. I don\'t know how to do it using XML and Java. The following picture is a model of the keyboard I want to make. It only needs numbers.

9条回答
  •  迷失自我
    2020-11-22 05:29

    System keyboard

    This answer tells how to make a custom system keyboard that can be used in any app that a user has installed on their phone. If you want to make a keyboard that will only be used within your own app, then see my other answer.

    The example below will look like this. You can modify it for any keyboard layout.

    The following steps show how to create a working custom system keyboard. As much as possible I tried to remove any unnecessary code. If there are other features that you need, I provided links to more help at the end.

    1. Start a new Android project

    I named my project "Custom Keyboard". Call it whatever you want. There is nothing else special here. I will just leave the MainActivity and "Hello World!" layout as it is.

    2. Add the layout files

    Add the following two files to your app's res/layout folder:

    • keyboard_view.xml
    • key_preview.xml

    keyboard_view.xml

    This view is like a container that will hold our keyboard. In this example there is only one keyboard, but you could add other keyboards and swap them in and out of this KeyboardView.

    
    
    
    
    

    key_preview.xml

    The key preview is a layout that pops up when you press a keyboard key. It just shows what key you are pressing (in case your big, fat fingers are covering it). This isn't a multiple choice popup. For that you should check out the Candidates view.

    
    
    
    

    3. Add supporting xml files

    Create an xml folder in your res folder. (Right click res and choose New > Directory.)

    Then add the following two xml files to it. (Right click the xml folder and choose New > XML resource file.)

    • number_pad.xml
    • method.xml

    number_pad.xml

    This is where it starts to get more interesting. This Keyboard defines the layout of the keys.

    
    
    
        
            
            
            
            
            
        
    
        
            
            
            
            
            
        
    
        
            
            
        
    
    
    

    Here are some things to note:

    • keyWidth: This is the default width of each key. The 20%p means that each key should take up 20% of the width of the parent. It can be overridden by individual keys, though, as you can see happened with the Delete and Enter keys in the third row.
    • keyHeight: It is hard coded here, but you could use something like @dimen/key_height to set it dynamically for different screen sizes.
    • Gap: The horizontal and vertical gap tells how much space to leave between keys. Even if you set it to 0px there is still a small gap.
    • codes: This can be a Unicode or custom code value that determines what happens or what is input when the key is pressed. See keyOutputText if you want to input a longer Unicode string.
    • keyLabel: This is the text that is displayed on the key.
    • keyEdgeFlags: This indicates which edge the key should be aligned to.
    • isRepeatable: If you hold down the key it will keep repeating the input.

    method.xml

    This file tells the system the input method subtypes that are available. I am just including a minimal version here.

    
    
    
        
    
    
    

    4. Add the Java code to handle key input

    Create a new Java file. Let's call it MyInputMethodService. This file ties everything together. It handles input received from the keyboard and sends it on to whatever view is receiving it (an EditText, for example).

    public class MyInputMethodService extends InputMethodService implements KeyboardView.OnKeyboardActionListener {
    
        @Override
        public View onCreateInputView() {
            // get the KeyboardView and add our Keyboard layout to it
            KeyboardView keyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view, null);
            Keyboard keyboard = new Keyboard(this, R.xml.number_pad);
            keyboardView.setKeyboard(keyboard);
            keyboardView.setOnKeyboardActionListener(this);
            return keyboardView;
        }
    
        @Override
        public void onKey(int primaryCode, int[] keyCodes) {
    
            InputConnection ic = getCurrentInputConnection();
            if (ic == null) return;
            switch (primaryCode) {
                case Keyboard.KEYCODE_DELETE:
                    CharSequence selectedText = ic.getSelectedText(0);
                    if (TextUtils.isEmpty(selectedText)) {
                        // no selection, so delete previous character
                        ic.deleteSurroundingText(1, 0);
                    } else {
                        // delete the selection
                        ic.commitText("", 1);
                    }
                    break;
                default:
                    char code = (char) primaryCode;
                    ic.commitText(String.valueOf(code), 1);
            }
        }
    
        @Override
        public void onPress(int primaryCode) { }
    
        @Override
        public void onRelease(int primaryCode) { }
    
        @Override
        public void onText(CharSequence text) { }
    
        @Override
        public void swipeLeft() { }
    
        @Override
        public void swipeRight() { }
    
        @Override
        public void swipeDown() { }
    
        @Override
        public void swipeUp() { }
    }
    

    Notes:

    • The OnKeyboardActionListener listens for keyboard input. It is also requires all those empty methods in this example.
    • The InputConnection is what is used to send input to another view like an EditText.

    5. Update the manifest

    I put this last rather than first because it refers to the files we already added above. To register your custom keyboard as a system keyboard, you need to add a service section to your AndroidManifest.xml file. Put it in the application section after activity.

    
        
            
                ...
            
    
            
                
                    
                
                
            
    
        
    
    

    That's it! You should be able to run your app now. However, you won't see much until you enable your keyboard in the settings.

    6. Enable the keyboard in Settings

    Every user who wants to use your keyboard will have to enable it in the Android settings. For detailed instructions on how to do that, see the following link:

    • How to set the default keyboard on your Android phone

    Here is a summary:

    • Go to Android Settings > Languages and input > Current keyboard > Choose keyboards.
    • You should see your Custom Keyboard on the list. Enable it.
    • Go back and choose Current keyboard again. You should see your Custom Keyboard on the list. Choose it.

    Now you should be able to use your keyboard anywhere that you can type in Android.

    Further study

    The keyboard above is usable, but to create a keyboard that other people will want to use you will probably have to add more functionality. Study the links below to learn how.

    • Creating an Input Method (Android documentation)
    • SoftKeyboard (source code from Android for a demo custom keyboard)
    • Building a Custom Android Keyboard (tutorial) (source code)
    • Create a Custom Keyboard on Android (tutsplus tutorial)
    • How to create custom keyboard for android (YouTube video: It is soundless but following along is how I first learned how to do this.)

    Going On

    Don't like how the standard KeyboardView looks and behaves? I certainly don't. It looks like it hasn't been updated since Android 2.0. How about all those custom keyboards in the Play Store? They don't look anything like the ugly keyboard above.

    The good news is that you can completely customize your own keyboard's look and behavior. You will need to do the following things:

    1. Create your own custom keyboard view that subclasses ViewGroup. You could fill it with Buttons or even make your own custom key views that subclass View. If you use popup views, then note this.
    2. Add a custom event listener interface in your keyboard. Call its methods for things like onKeyClicked(String text) or onBackspace().
    3. You don't need to add the keyboard_view.xml, key_preview.xml, or number_pad.xml described in the directions above since these are all for the standard KeyboardView. You will handle all these UI aspects in your custom view.
    4. In your MyInputMethodService class, implement the custom keyboard listener that you defined in your keyboard class. This is in place of KeyboardView.OnKeyboardActionListener, which is no longer needed.
    5. In your MyInputMethodService class's onCreateInputView() method, create and return an instance of your custom keyboard. Don't forget to set the keyboard's custom listener to this.

提交回复
热议问题