Let’s body a custom keyboard for Android

This column will allocution you through the action of creating your own custom Android keyboard. Ideal for those attractive to aggrandize their Android development skills, personalize their own adaptable experience, or actualize the abutting SwiftKey!

When cerebration of building an Android app, we generally anticipate of article with a awning and a independent function. It could be a game, or a apparatus to accomplish a accepted task.

But apps can appear in a array of shapes and sizes. You could body a account that runs in the accomplishments and agilely makes activity easier for the user. You could actualize a widget, or a launcher. How about a keyboard?

Upgrading the software keyboard on your accessory is one of the best abstruse agency to adapt a device. Best of us use the keyboard as our primary ascribe method. It’s basic to about every alternation with your phone. In the best-case scenario, it can accomplish aggregate quicker, easier, and beneath error-prone.

Keyboard apps can be awful acknowledged for this acumen too; aloof attending at the beyond of Swype and SwiftKey.

Whether you aloof appetite to booty your Android customization to the abutting level, or you’d like to advertise a accomplished new way to collaborate with a acute device, apprehend on and let’s analyze how to actualize an Android keyboard.

Note: This activity is almost simple and requires mostly artful and pating XML script. However, it does accommodate some added avant-garde concepts like casework and inheritance. If you’re blessed to chase forth to get a keyboard running, again anyone should be able to carbon the app. If you appetite to accept what aggregate does, this is a acceptable average activity to blanket your arch around. You will of advance charge Android Studio and the Android SDK already set-up.

To body our custom keyboard, we’re aboriginal activity to charge to actualize a new xml file, which will ascertain the blueprint and actualization of our keyboard. That book will be alleged keyboard_view.xml. To actualize this, appropriate bang on the “layout” binder in your “res” agenda and accept “layout ability file.” In the chat box that ancestor up, bright the argument area it says “Root element” and alpha accounting “keyboard.” Baddest the aboriginal advantage which comes up, which should be: android.inputmethodservice.KeyboardView. Call the book keyboard_view.xml (remember, no capitals for resources!).

You will be greeted by a book attractive like this:

We’re activity to add a few elements now:

We’ve assigned an ID actuality so we can accredit to the keyboard after in our code. The cipher aligns our keyboard to the basal of the awning and the accomplishments blush is set to colorPrimary. This blush is the one set in our values > colors.xml book — it’s accessible to change after on. So aloof hop in there and change the corresponding blush cipher to change the attending a little.

We’ve additionally referred to addition blueprint for “keyboard preview.” In case you’re abrading your head, that’s the angel of the key that flashes up in a ample chantry back you accomplish contact. This assures the user they hit the appropriate key.

As you’ve possibly guessed, this agency we charge addition new blueprint file, the above keyboard_preview.xml. Create it in aloof the aforementioned way, admitting the basis aspect this time is TextView.

Add this cipher and you’ll ascertain the blush of the aboveboard and the blush of the letter actualization in the square. I additionally set the alignment to center, which ensures it looks the way it should.

The abutting new XML book is alleged method.xml. This will go in your assets binder and accept the basis aspect input-method. This book will acquaint Android what blazon of ascribe is accessible through your app. Again, you appetite to alter the boilerplate cipher that’s there so that it reads like this:

You can additionally put advice such as accent in actuality after on.

This is area we will actualize the blueprint for our keyboard — it’s about the fun part!

That will go in a new agenda you’ll actualize (res — xml) and I’m calling mine keys_layout.xml. Alter the cipher that’s there with this:

This is what we’ll be clearing with the keys and their behaviors.

We’ve congenital a agglomeration of XML files and now we’re accessible to alpha accepting some fun. It’s time to actualize the blueprint of the keys!

This is what I used. It’s basically a hardly tweaked adaptation of a keyboard blueprint I begin online, with the keys all in accepted rows. It’s not absolutely beautiful, but it’ll do.

You’ll apprehension a few absorbing things here. The android:codes tell us what anniversary key needs to do. This is what we’ll be accepting through our account anon and you charge to accomplish abiding the keyLabel (the argument on the keys) curve up with what it absolutely does. Well, unless your cold is to actualize a “troll keyboard.”

If you abode added than one cipher afar by commas, your keys will annal through those options if the user bifold or amateur taps. That way we can accomplish a keyboard that works like the old T9 numpad keyboards on Nokia phones, for instance.

Negative codes represent the constants in the keyboard class. -5 is the agnate of KEYCODE_DELETE. Play around, use your imagination, and see if you can appear up with a “better keyboard.”

An accessible best is to accomplish the added accepted keys a little larger. That’s what I’ve started doing.

Now it’s time to actualize a java class. This is activity to be alleged MyInputMethodService and, as the name suggests, it’s activity to be a service. The superclass will be android.inputmethodservice, acceptation it will accede backdrop from that affectionate of chic and behave like an ascribe adjustment account should (politely).

Under Interface(s), we’ll be implementing OnKeyboardActionListener. Alpha accounting and again baddest the advancement that springs up.

See Also: hack hike

Being a service, this agency your app can run in the accomplishments and again accept out for the moment back it is bare – back the user selects an adapt argument in addition appliance for example.

Your chic will be accent red back this is generated, which is because it needs to apparatus the methods from InputMethodService. You can accomplish this automatically by appropriate beat on your chic and allotment generate — apparatus methods.

Here’s what it should attending like:

You additionally charge to override the onCreateInputView() method, which is activity to grab the keyboard appearance and add the blueprint assimilate it.

Now add the afterward code, canonizing to acceptation all classes as necessary.

When the ascribe appearance is created, it takes the blueprint book keyboard_view and uses it to ascertain how it looks. It additionally adds the keys_layout book we created and allotment the appearance for the arrangement to use.

I’ve additionally added a Boolean (true or apocryphal variable) alleged caps so we can accumulate clue of caps-lock.

The added important adjustment here, is the one administration key presses. Try this:

This is a about-face account which looks for the key cipher and acts accordingly. Back the user clicks specific keys, the cipher will change course. KEYCODE_SHIFT changes our caps Boolean, sets the keyboard to “Shifted,” and again invalidates the keys (to alter them).

commitText artlessly sends argument (which can accommodate assorted characters) to the ascribe field. sendKeyEvent will accelerate contest like “return” to the app.

The chic in its absoluteness should attending like this:

In adjustment to analysis your new keyboard, you’ll charge to add it via your device’s settings. To do this, go to Language & Ascribe — Virtual Keyboard — Manage Keyboards and about-face on the keyboard you created. Baddest “OK” a few times to abolish the notifications.

Now accessible up any app with a argument ascribe and accompany up your keyboard. You’ll apprehension a little keyboard figure in the basal right. Baddest that and again aces your app from the list. If all has gone to plan, your keyboard should now bounce to life!

This is a little ambagious for new users, so if you plan on affairs this app, it ability be a acceptable abstraction to add some argument to the MainActivity.Java file, answer how to baddest the keyboard. You could additionally use this in adjustment to add some customization or settings for the users to tweak.

You could add affluence of customization options. How about absolution the user change the acme and admeasurement of their keyboard? You could let them change the colors, use altered icons for the keys (android:keyicon), or change the images absolutely (android:keybackground=@drawable/). For added avant-garde options — like alteration the blush of anniversary alone key — you’ll charge to use Java, not XML.

Another accepted affection of keyboards is to add sounds on anniversary click. You can do this calmly by abacus a new adjustment in your account and calling it onKey.

The nice affair is that Android absolutely provides some sounds for us accessible to use, so we can do this actual easily:

Now aloof use playSound() at the top of the onKey method and accomplish abiding to actualize a vibrator and audio administrator (private AudioManager am; clandestine Virbator v;). You could aloof as calmly bandy out the key sounds for your own in the assets folder, or change the continuance and behavior of the virbration.

Now you accept your actual own custom keyboard! Addition claiming ticked off of your Android development list. Play about with altered key sizes, customization, and appearance to actualize the absolute accounting experience.

A keyboard can accomplish every alternation quicker, easier and beneath decumbent to errors.

Play about with altered key sizes, customization and appearance to actualize the absolute accounting experience.

Layout files. LOTS of blueprint files

Designing your keyboard

At your service

Testing it out and customization

Closing comments

android:id="@ id/keyboard_view"
android:keyPreviewLayout="@Layout/key_preview"
android:layout_alignParentBottom="true"
android:background="@color/colorPrimary">

 
 

     
 

 
     
 

 
     
         
         
         
         
         
         
         
         
         
         
         
     
     
         
         
         
         
         
         
         
         
         
         
     
     
         
         
         
         
         
         
         
         
         
         
     
     
         
         
         
         
         
         
         
         
         
         
     
     
         
         
         
         
     
 
public chic MyInputMethodService extends InputMethodService accouterments KeyboardView.OnKeyboardActionListener {
 
 
     accessible MyInputMethodService() {
         super();
     }
     
     @Override
     accessible abandoned onPress(int i) {
 
     }
 
     @Override
     accessible abandoned onRelease(int i) {
 
     }
 
     @Override
     accessible abandoned onKey(int i, int[] ints) {
 
     }
 
     @Override
     accessible abandoned onText(CharSequence charSequence) {
 
     }
 
     @Override
     accessible abandoned swipeLeft() {
 
     }
 
     @Override
     accessible abandoned swipeRight() {
 
     }
 
     @Override
     accessible abandoned swipeDown() {
 
     }
 
     @Override
     accessible abandoned swipeUp() {
 
     }
 }

 clandestine KeyboardView keyboardView;
 clandestine Keyboard keyboard;
 
 clandestine boolean caps = false;
 
 @Override
 accessible Appearance onCreateInputView() {
     keyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view, null);
     keyboard = new Keyboard(this, R.xml.keys_layout);
     keyboardView.setKeyboard(keyboard);
     keyboardView.setOnKeyboardActionListener(this);
     acknowledgment keyboardView;
 }
@Override
 accessible abandoned onKey(int primaryCode, int[] keyCodes) {
     InputConnection inputConnection = getCurrentInputConnection();
     if (inputConnection != null) {
         switch(primaryCode) {
             case Keyboard.KEYCODE_DELETE :
                 CharSequence selectedText = inputConnection.getSelectedText(0);
 
                 if (TextUtils.isEmpty(selectedText)) {
                     inputConnection.deleteSurroundingText(1, 0);
                 } abroad {
                     inputConnection.commitText("", 1);
                 }
             case Keyboard.KEYCODE_SHIFT:
                 caps = !caps;
                 keyboard.setShifted(caps);
                 keyboardView.invalidateAllKeys();
                 break;
             case Keyboard.KEYCODE_DONE:
                 inputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
 
                 break;
             absence :
                 burn cipher = (char) primaryCode;
                 if(Character.isLetter(code) && caps){
                     cipher = Character.toUpperCase(code);
                 }
                 inputConnection.commitText(String.valueOf(code), 1);
 
         }
     }
 
 }
public chic MyInputMethodService extends InputMethodService accouterments KeyboardView.OnKeyboardActionListener {
 
     clandestine KeyboardView keyboardView;
     clandestine Keyboard keyboard;
 
     clandestine boolean caps = false;
 
     @Override
     accessible Appearance onCreateInputView() {
         keyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view, null);
         keyboard = new Keyboard(this, R.xml.keys_layout);
         keyboardView.setKeyboard(keyboard);
         keyboardView.setOnKeyboardActionListener(this);
         acknowledgment keyboardView;
     }
 
     @Override
     accessible abandoned onPress(int i) {
 
     }
 
     @Override
     accessible abandoned onRelease(int i) {
 
     }
 
 
 
     @Override
     accessible abandoned onKey(int primaryCode, int[] keyCodes) {
         InputConnection inputConnection = getCurrentInputConnection();
         if (inputConnection != null) {
             switch(primaryCode) {
                 case Keyboard.KEYCODE_DELETE :
                     CharSequence selectedText = inputConnection.getSelectedText(0);
 
                     if (TextUtils.isEmpty(selectedText)) {
                         inputConnection.deleteSurroundingText(1, 0);
                     } abroad {
                         inputConnection.commitText("", 1);
                     }
                 case Keyboard.KEYCODE_SHIFT:
                     caps = !caps;
                     keyboard.setShifted(caps);
                     keyboardView.invalidateAllKeys();
                     break;
                 case Keyboard.KEYCODE_DONE:
                     inputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
 
                     break;
                 absence :
                     burn cipher = (char) primaryCode;
                     if(Character.isLetter(code) && caps){
                         cipher = Character.toUpperCase(code);
                     }
                     inputConnection.commitText(String.valueOf(code), 1);
 
             }
         }
 
     }
 
 
     @Override
     accessible abandoned onText(CharSequence charSequence) {
 
     }
 
     @Override
     accessible abandoned swipeLeft() {
 
     }
 
     @Override
     accessible abandoned swipeRight() {
 
     }
 
     @Override
     accessible abandoned swipeDown() {
 
     }
 
     @Override
     accessible abandoned swipeUp() {
 
     }
 }
private abandoned playSound(int keyCode){

    v.vibrate(20);
    am = (AudioManager)getSystemService(AUDIO_SERVICE);
    switch(keyCode){
        case 32:
            am.playSoundEffect(AudioManager.FX_KEYPRESS_SPACEBAR);
            break;
        case Keyboard.KEYCODE_DONE:
        case 10:
            am.playSoundEffect(AudioManager.FX_KEYPRESS_RETURN);
            break;
        case Keyboard.KEYCODE_DELETE:
            am.playSoundEffect(AudioManager.FX_KEYPRESS_DELETE);
            break;
        default: am.playSoundEffect(AudioManager.FX_KEYPRESS_STANDARD);
    }
}

Comments