Custom View Exercise-Kanji keyboard

Source: Internet
Author: User
Tags delete key relative touch visibility
Custom View Exercise-Kanji keyboard Practice Source

Android custom keyboard final effect diagram of Chinese character keyboard

Basic Knowledge

The following is excerpted from the above article

First, soft keyboard introduction

The implementation of the soft keyboard is mainly used in the system of two classes: Keyboard and Keyboardview.
Keyboard class source code is introduced: Listener for virtual keyboard events.
Keyboardview class source code is introduced: A view that renders a virtual {@link Keyboard}. It handles rendering of keys and detecting key presses and touch movements. That is, it handles drawing keyboards and detecting keystrokes and touch actions.
There are a lot of ways in it, in our custom soft keyboard a lot of properties, we need to use this class to set. Like what:

Keyboardview = (Keyboardview) Act.findviewbyid (R.id.keyboard_view);  
Keyboardview.setkeyboard (k);  
Keyboardview.setenabled (true);  
Keyboardview.setpreviewenabled (true);
Keyboardview.setvisibility (view.visible);
Keyboardview.setonkeyboardactionlistener (listener);

Learn some of the source code, it can be we know why we write this, why to do so.

Second, the layout of the digital soft keyboard

Create a new XML folder under Res, create a new Symbols.xml file in the XML folder, this layout file is mainly to implement the layout of the digital soft keyboard, each key has a codes value, in the class is the codes value to listen to each button.

<?xml version= "1.0" encoding= "Utf-8"?> <keyboard xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:keywidth=" 20%p "android:horizontalgap=" 0px "android:verticalgap=" 0px "android:keyheight=" @dimen/k Ey_height "> <Row> <key android:codes=" android:keylabel= "1"/> <key android:code S= "android:keylabel=" 2 "/> <key android:codes=" Wuyi "android:keylabel=" 3 "/> <key Android:co Des= "android:keylabel=" 4 "/> <key android:codes="-5 "android:keyicon=" @drawable/sym_keyboard_delete "/&G
    T </Row> <Row> <key android:codes= "android:keylabel=" 5 "/> <key Android : codes= "android:keylabel=" 6 "/> <key android:codes=" "" android:keylabel= "7"/> <key Andro

    Id:codes= "android:keylabel=" 8 "/> <key android:codes="-2 "android:keylabel=" Chinese "/> </Row>       
        <Row><key android:codes= "android:keylabel=" 9 "/> <key android:codes=" "android:keylabel=" 0 "/>
            <key android:codes= "android:keylabel=". "/> <key android:codes="-3 "android:keywidth=" 40%p " Android:isrepeatable= "true" android:keylabel= "complete"/> </Row> </Keyboard>

The numeric keypad interface is as follows:

In the above keyboard definition, the keyboard description is a soft keyboard definition file, the row element indicates that this is the definition of a row of keys, the key element indicates that this is a key definition. The key element defines each key by some attributes, and here are some of the commonly used property descriptions:
Codes: Represents the output value of the key, can be a Unicode value or a comma (,) to split multiple values, or a string. Escape special characters by "\" in the string, for example ' \ n ' or ' \uxxxx '. Codes is usually used to define the key code, such as the number of keys in the figure 1 corresponds to 49, if the provided is a comma-separated by multiple values and the normal phone input keyboard to switch between multiple values.
Keylabel: Represents the text content of the key display.
Keyicon: Represents the icon content of the button display, and if specified, displays the text as a picture when it is displayed.
Keywidth: Represents the width of the key, can be a precise value or relative value, for the exact value of supporting a variety of units, such as: pixels, inches, etc. relative value is the percentage relative to the base value, which ends with% or%p, where%p is relative to the parent container.
Keyheight: Represents the height of the button, the value is the same as above.
HorizontalGap: Represents the Gap before the key (horizontal direction), the value ibid.
Issticky: Specifies whether the key is sticky. For example, the shift-case toggle button has two states, press state and normal state, and evaluates to TRUE or FALSE.
Ismodifier: Specifies whether the key is a function key (modifier key), such as Alt or Shift, and evaluates to TRUE or FALSE.
Keyoutputtext: Specifies the text content of the key output and takes the value as a string.
Isrepeatable: Specifies whether the key is repeatable, or false if long press the key to trigger a repeat key event.
Keyedgeflags: Specifies the alignment instruction for the key, with a value of left or right.

When we set code for each key, it is fixed by some of the attributes defined in the keyboard class, such as fallback, switchover, completion, and so on.

  public static final int keycode_shift =-1;  
  public static final int keycode_mode_change =-2;  
  public static final int keycode_cancel =-3;  
  public static final int keycode_done =-4;  
  public static final int keycode_delete =-5;  
  public static final int keycode_alt =-6;

Knowing this, we will not have too much doubt. It is also said that every button we customize will have a codes value, such as fallback we write:

<key android:codes= "-5" android:keyicon= "@drawable/sym_keyboard_delete"/>

In the Listening department is:

if (Primarycode = = Keyboard.keycode_delete) {}

This means that you are listening for a fallback event.

Second, the acquisition of the codes of Chinese character keyboard

Each key has a codes value, and this codes is the encoded value of a Chinese character in the UTF16 standard.

There are two ways to find the encoding of a Chinese character:
1, directly find the UTF16 table, you can refer to:
http://blog.csdn.net/lintax/article/details/51866861
If the number of Chinese characters is more, it is a matter of great bother to type XML with the exact corresponding character of Chinese characters and coded values.
2, the program obtains

    /**
     * Generate codes and Keylabel in XML file */public
    static void Main (string[] args) {
        string[] names = {"Zhao", "Qian", "Sun" , "Li", "Zhou", "WU", "Zheng", "Wang", "Feng", "Chen"};
        char c;
        int i;
        for (String str:names) {
            c = str.tochararray () [0];
            i = C;
            System.out.println ("<key android:codes=\" "+ i +" \ "android:keylabel=\" "+ C +" \ "/>");
        }
    }

The resulting XML content is:

<key android:codes= "36213" android:keylabel= "Zhao"/> <key
android:codes= "38065" android:keylabel= "Money"/ >
<key android:codes= "23385" android:keylabel= "Sun"/> <key
android:codes= "26446" Android: Keylabel= "Li"/>

Write these obtained codes to the Res/xml/chinese.xml file.
Code See:
Chinese.xml

Iii. layout file for the example
A edittext and a hidden custom keyboard.

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout android:id= "@+id/activity_main" Xmlns:andr Oid= "Http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" Andro id:layout_height= "Match_parent" > <edittext android:id= "@+id/etcontent" Android:layout_width= "Ma Tch_parent "android:layout_height=" wrap_content "android:textcolor=" #333 "/> <android.inputmetho Dservice. Keyboardview android:id= "@+id/keyboardview" android:layout_width= "Match_parent" Android:layout_hei ght= "200DP" android:layout_alignparentbottom= "true" android:focusable= "true" Android:focusableinto Uchmode= "true" android:keybackground= "@drawable/keyboard_bg" android:keytextcolor= "#FFF" android:k eypreviewlayout= "@layout/key_preview_layout" android:keypreviewheight= "40DP" android:visibility= "Gone"/&gt

; </relativElayout> 

Note These four attributes, all of which can be seen in the name.

android:keybackground= "@drawable/keyboard_bg"
android:keytextcolor= "#FFF"
android:keypreviewlayout= "@ Layout/key_preview_layout "
android:keypreviewheight=" 40DP "

The preview layout key_preview_layout.xml content is:

<?xml version= "1.0" encoding= "Utf-8"?> <textview
xmlns:android= "http://schemas.android.com/apk/res/ Android "
          android:layout_width=" wrap_content "
          android:layout_height=" Wrap_content "
          android: Background= "#ff8888ff"
          android:gravity= "center"
          android:textcolor= "@android: Color/white"
          android: Textsize= "30DP"/>

Iv. using a custom keyboard
Main steps
1. Bind the codes in Chinese.xml to the keyboard.
2. Setting the properties of the Keyboardview
3. Set the Onkeyboardactionlistener listener. The main implementation of the OnKey () and Onpress () methods
4. Disable the system's keyboard and EditText context menu.
5. Implement the EditText Ontouchlistener listener to display the custom keyboard.

public class Mainactivity extends Appcompatactivity {private EditText etcontent;

    Private Keyboardview Keyboardview;
        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
        Setcontentview (R.layout.activity_main);
        Etcontent = (EditText) Findviewbyid (r.id.etcontent);
        Keyboardview = (Keyboardview) Findviewbyid (R.id.keyboardview);
        Keyboard Chinesekeyboard = new Keyboard (this, R.xml.chinese);
        Keyboardview.setkeyboard (Chinesekeyboard);
        Keyboardview.setenabled (TRUE);
        Keyboardview.setpreviewenabled (TRUE);

        Keyboardview.setonkeyboardactionlistener (listener); Disable the system's own keyboard if (Build.VERSION.SDK_INT <= build.version_codes.
        GINGERBREAD_MR1) {//API < Etcontent.setinputtype (inputtype.type_null);
            } else {This.getwindow (). Setsoftinputmode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
try {                class<edittext> cls = Edittext.class;
                Method Setshowsoftinputonfocus = Cls.getmethod ("Setshowsoftinputonfocus", Boolean.class);
                Setshowsoftinputonfocus.setaccessible (TRUE);
            Setshowsoftinputonfocus.invoke (Etcontent, false);
            } catch (Exception e) {e.printstacktrace (); }}//Disable edittext of the Etcontent.setcustomselectionactionmodecallback context menu (new Actionmode.callback () {//Here you can add your own menu options and return True @Override public boolean oncreateactionmode (Action
            Mode mode, menu menu) {return false;//return false indicates mask actionmode menu} @Override
            public boolean Onprepareactionmode (actionmode mode, menu menu) {return false;
                } @Override public boolean onactionitemclicked (actionmode mode, MenuItem item) {
       return false;     } @Override public void Ondestroyactionmode (Actionmode mode) {}});
            Click EditText Pop-up Chinese keyboard etcontent.setontouchlistener (new View.ontouchlistener () {@Override
                public Boolean OnTouch (view view, Motionevent motionevent) {showkeyboard ();
            return false;

    }
        });
        } 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.gone);
        }} private Keyboardview.onkeyboardactionlistener listener = new Keyboardview.onkeyboardactionlistener () { @Override public void onpress (int primarycode) {//delete key and finish key do not display preview if (Primarycode = = Keyboard.keycode_delete | | primarycode = = Keyboard.keycode_
            CANCEL) {keyboardview.setpreviewenabled (false);
            } else {//other keys Display preview keyboardview.setpreviewenabled (TRUE); }} @Override public void onrelease (int primarycode) {} @Override Pub
            LIC void OnKey (int primarycode, int[] keycodes) {Editable Editable = Etcontent.gettext ();
                int start = Etcontent.getselectionstart ();//Get cursor selected start position if (Primarycode = = Keyboard.keycode_cancel) {//Finish
            Hidekeyboard ();  } else if (Primarycode = = Keyboard.keycode_delete) {//BACKSPACE if (editable! = null && editable.length ()
                    > 0) {if (Start > 0) {editable.delete (start-1, start); }}} else {//Kanji key EDitable.insert (Start, character.tostring (char) primarycode)); }} @Override public void Ontext (charsequence text) {} @Override Publi
        c void Swipeleft () {} @Override public void Swiperight () {} @Override
public void Swipedown () {} @Override public void Swipeup () {}};
 }
Learning Knowledge

Customize the entire process of the keyboard.
(1) Obtain the required Unicode characters, constituting the XML map codes and labels, as the key to display;
(2) using the system's own keyboardview as a keyboard component;
(3) The binding key is mapped to the keyboard object. Sets the Keyboardview property. Set the preview layout;
(4) Disable the system keyboard and disable the EditText context menu;
(5) Set Onkeyboardactionlistener listener for Keyboardview, implement OnKey () and Onpress () method;
(6) Add EditText Ontouchlistener Monitor to display the custom keyboard.

Keys are built into the keyboard, and these buttons are not to be changed.

  public static final int keycode_shift =-1;  
  public static final int keycode_mode_change =-2;  
  public static final int keycode_cancel =-3;  
  public static final int keycode_done =-4;  
  public static final int keycode_delete =-5;  
  public static final int keycode_alt =-6;

Other reading articles:
Android Custom keyboard Chinese character keyboard
Custom keyboard implementation principles and three examples
Android custom keyboard (fix pop-up tips for font color issues)
Simple custom security keyboard (only letters, numbers, partial symbols)

Github:https://github.com/cizkey/custompractice/tree/master/chinesekeyboard

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.