Как сделать свою клавиатуру на телефоне
Перейти к содержимому

Как сделать свою клавиатуру на телефоне

  • автор:

Как написать свою клавиатуру для Android

Здравствуйте. В данной статье я постараюсь рассказать и показать основные моменты написания собственной клавиатуры для Android’а. Статья предназначена для разработчиков, которые с этим не сталкивались, но имеют опыт знакомства с Android’ом.

Сразу оговорюсь, что мнение и код автора не являются истинной в последней инстанции, а ваши предложения и критика лишь приветствуются. И если не охота все читать, ссылка на исходники в конце статьи.

Для начала необходимо создать пустой Android проект без Activity. После этого приступим к подготовке .xml файлов, которые будут описывать Android’у нашу клавиатуру.

Базовый layout-файл, keyboard.xml

Содержит в себе View класс Android’а под названием KeyboardView и описывает внешний вид клавиатуры.

  • android: keyPreviewHeight — задает высоту элемента подсказки, на котором отображается текущая нажатая клавиша.
  • android:keyPreviewLayout — указываем layout-файл, который описывает внешний вид preview’шки.

Важный момент, атрибут background является обязательным, если его не указать, то при каждом нажатии клавиши ваша клавиатура будет падать.

Описание раскладки

Итак, мы подготовили 2 .xml файла, которые описывают внешний вид, теперь настал черед описать саму раскладку клавиатуры. Назовем этот файл keys_definition_ru.xml и находится он будет в xml ресурсах проекта. Здесь будет представлен лишь его кусок, так как файл достаточно большой.

Все атрибуты описывать не будем, лишь «не очевидные».

  • android:horizontalGap — горизонтальный отступ между клавишами
  • android: verticalGap — вертикальный отступ
  • android:codes — код нужного символа в html utf-8 (и не только utf-8, подробнее в оф. документации)
  • android:keyEdgeFlags — атрибут может применять значение left или right. Эти атрибуты добавляются клавишам, которые расположены в самом левом крае или самом правом крае клавиатуры
  • android:isRepeatable — повторять действие клавиши при долгом нажатии (обычно используется на пробеле или backspace)

InputMethodService — сервис клавиатуры

Теперь, после того как мы создали все необходимые xml файлы, приступаем к описанию сервиса, который будет слушать события InputMethod.

Для этого создадим сервис, наследуясь от InputMethodService и сразу реализуем интерфейс KeyboardView.OnKeyboardActionListener. В итоге у вас получиться набор методов, которые вы можете переопределить и наполнить необходимой функциональностью, которые позволяют широко кастомизировать вашу клавиатуру. Но здесь я приведу лишь примеры базовых моментов.

Одним из методов жизненного цикла InputMethodService является onCreateInputView внутри которого мы создаем View клавиатуры и привязываем к ней необходимые листенеры.

Событие onKey срабатывает между onPress и onRelease, на вход им подается код нажатой клавиши.

Создание пользовательской клавиатуры на Android .

Большинство устройств Android не имеют клавиатуры. Вместо этого они полагаются на виртуальную или экранную клавиатуру для ввода текста. Если вы используете персонализацию Android, то знание о создании пользовательской, приятной клавиатуры может вывести ваше хобби на совершенно новый уровень.

Используя Android SDK, вы можете быстро создать экранную клавиатуру с удивительно небольшим количеством строк кода, поскольку SDK выполняет множество задач простого уровня, таких как распознавание касаний клавиш, рисование клавиатуры и установление соединений между клавиатурой и поля ввода.

В этом уроке вы узнаете, как создать полноценную функциональную клавиатуру, которая может служить для вас на вашем устройстве Android по умолчанию.

1. Предпосылки

Вам понадобится комплект Eclipse ADT Bundle. Вы можете загрузить его с веб-сайта разработчика Android .

2. Создать новый проект

Запустите программу Eclipse и создайте новое приложение для Android. Назовите это приложение SimpleKeyboard. Убедитесь, что вы выбрали уникальное имя пакета. Установите минимально необходимый SDK на значение Android 2.2 и установите целевой SDK на значение Android 4.4

Создание пользовательской клавиатуры на Android.

Это приложение не будет иметь никаких действий, поэтому снимите флажок с Создать мероприятие и нажмите Готово.

Создание пользовательской клавиатуры на Android.

3. Отредактируйте манифест

Экранная клавиатура рассматривается как Input Method Editor (IME) для операционной системы Android. IME объявляется как Service в AndroidManifest.xml, который использует разрешение BIND_INPUT_METHOD и отвечает за android.view.InputMethod .

Добавьте следующие строки в тег application файла манифеста:

4. Создайте метод.

Тег service в файле манифеста содержит meta-data , который ссылается на файл XML с именем method.xml. Без этого файла операционная система Android не признает наш Service в качестве действительной IME-службы. Файл содержит сведения о методе ввода и его подтипах. Для перевода нашей клавиатуры на другой язык мы выбираем один подтип en_US. Создайте каталог res/xml, если его нет, и добавьте к нему файл method.xml. Содержимое файла должно быть следующим:

5. Редактирование строк.xml

Строки, используемые этим приложением, определены в файле theres/values/strings.xml. Нам понадобятся следующие три строки:

  • имя приложения
  • ярлык IME
  • ярлык подтипа IME

Обновите файл strings.xml, чтобы он имел следующее содержимое:

6. Определите макет клавиатуры

Макет нашей клавиатуры содержит только KeyboardView . Атрибут layout_alignParentBottom имеет значение true , чтобы клавиатура отображалась в нижней части экрана.

Создайте файл с именем res/layout/keyboard.xml и замените его содержимое следующим текстом:

KeyPreviewLayout — это макет недолговечного всплывающего окна, которое появляется при каждом нажатии клавиши на клавиатуре. Он содержит единственный TextView . Создайте файл res/layout/preview.xml и добавьте к нему следующее:

6. Определите клавиши клавиатуры

Детали клавиш клавиатуры и их позиции указаны в файле XML. Каждый ключ имеет следующие атрибуты:

  • keyLabel : этот атрибут содержит текст, отображаемый на клавише.
  • codes : Этот атрибут содержит значения unicode символов, которые представляет ключ.

Например, чтобы определить ключ для буквы A, атрибут codes должен иметь значение 97, а атрибут keyLabel должен быть установлен в A.

Если с ключом связано несколько кодов, тогда символ, который представляет собой ключ, будет зависеть от количества нажатий, которые получает ключ. Например, если ключ имеет коды 63, 33 и 58:

  • одно нажатие на клавишу приводит к символу «?»
  • два быстрых нажатия приводят к символу «!»
  • три отображают символ «:»

Ключ может также иметь несколько необязательных атрибутов:

  • keyEdgeFlags : этот атрибут может принимать значение left или right . Этот атрибут обычно добавляется к крайним левым и правым клавишам в строке.
  • keyWidth : этот атрибут определяет ширину клавиши. Обычно это определяется в виде процентного значения.
  • isRepeatable : если для этого атрибута установлено значение true , длительное нажатие клавиши будет повторять действие клавиши несколько раз. Обычно значение true установлено для клавиш удаления и пробела.

Клавиши клавиатуры сгруппированы в виде строк. Рекомендуется ограничить количество клавиш в строке до десяти, причем каждая клавиша имеет ширину, равную 10% от клавиатуры. В этом уроке высота клавиш установлена в 60dp. Это значение можно отрегулировать, но значения менее 48dp не рекомендуются. У нашей клавиатуры будет пять рядов ключей.

Теперь мы можем идти вперед и разрабатывать клавиатуру. Создайте новый файл с именем res/xml/qwerty.xml и замените его содержимое следующим текстом:

Возможно, вы заметили, что некоторые ключи имеют отрицательные значения в атрибуте codes . Отрицательные значения равны предопределенным константам для класса Keyboard . Например, значение -5 равно значению Keyboard.KEYCODE_DELETE .

7. Создание класса Service

Создайте новый класс Java и назовите его SimpleIME.java. InputMethodService и реализовать интерфейс OnKeyboardActionListener . Интерфейс OnKeyboardActionListener содержит методы, вызываемые при касании или нажатии клавиш экранной клавиатуры.

Класс SimpleIME должен иметь три переменные-члена:

  • KeyboardView , ссылающийся на представление, определенное в макете
  • Экземпляр Keyboard , который назначен для KeyboardView
  • boolean , сообщает нам включен ли caps lock

После объявления этих переменных и добавления методов интерфейса OnKeyboardActionListener класс SimpleIME должен выглядеть следующим образом:

Когда клавиатура создана, вызывается метод onCreateInputViewmethod . Здесь могут быть инициализированы все переменные Service . Обновите реализацию метода onCreateInputView , как показано ниже:

Затем мы создаем метод, который воспроизводит звук при нажатии клавиши. Мы используем класс AudioManager для воспроизведения звука. Android SDK включает в себя несколько стандартных звуковых эффектов по умолчанию для нажатия клавиш, и они используются в методе playClick .

Наконец, обновите метод onKey , чтобы наше приложение могло взаимодействовать с полями ввода (как правило, EditText ) других приложений.

Метод getCurrentInputConnection используется для получения соединения с полем ввода другого приложения. После подключения мы можем использовать следующие методы:

  • commitText для добавления одного или нескольких символов в поле ввода
  • deleteSurroundingText для удаления одного или нескольких символов поля ввода
  • sendKeyEvent для отправки событий, таких как KEYCODE_ENTER , во внешнее приложение

Всякий раз, когда пользователь нажимает клавишу на клавиатуре, onKey вызывается с использованием значения unicode ключа в качестве одного из его параметров. Основываясь на этом значении, клавиатура выполняет одно из следующих действий:

  • В случае, если код следующий — KEYCODE_DELETE , то один символ слева от курсора удаляется с помощью метода deleteSurroundingText .
  • В случае, Если код — KEYCODE_DONE , событие ключа KEYCODE_ENTER запускается.
  • В случае, Если код — KEYCODE_SHIFT , значение caps изменяется, а состояние нажатия клавиатуры обновляется с помощью метода setShifted . При изменении состояния нажатия клавиши должны быть перерисованы, чтобы надписи клавиш были обновлены. InvalidateAllKeys используется для перерисовки всех ключей.
  • Для всех других кодов код просто преобразуется в символ и отправляется в поле ввода. Если код представляет букву алфавита, а переменная caps имеет значение true , то символ преобразуется в верхний регистр.

Обновите метод onKey , чтобы он выглядел так:

8. Тестирование клавиатуры

Итак, экранная клавиатура готова к тестированию. Скомпилируйте и запустите её на устройстве Android. Это приложение не имеет Activity , что означает, что оно не появится в панели запуска. Чтобы использовать её, его следует сначала активировать в настройках устройства.

Создание пользовательской клавиатуры на Android.

После активации Simple IME откройте любое приложение, которое позволяет вводить текст (например, любое приложение для обмена сообщениями) и понажимайте по одному из его полей ввода. Вы должны увидеть значок клавиатуры в области уведомлений. В зависимости от вашего устройства вы можете щелкнуть по этому значку или перетащить панель уведомлений вниз и выбрать Simple IME в качестве метода ввода. Теперь вы можете использовать новую клавиатуру.

How to create a custom keyboard with Xamarin Forms (Android)

Fabricio Bertani

Some time ago a client requested a special keyboard for his application, which had to have certain conditions that the regular Android keyboard didn’t meet.

Researching

The first option that came to mind was to add a disabled Entry with a GestureRecognizer that displays a control with an animation to emulate the appearance of the keyboard, but quickly discard the idea as it wasn’t reusable.
The best option was taking the native path, so I spent quite time researching, but I only found solutions that leads to create a keyboard as a service. I knew that our client wouldn’t like the idea of having to download a separate keyboard to only use it in the application and I needed a solution that should work with Xamarin Forms!
As I had to think about its implementation in Xamarin Forms I decided that the best option was to try with a Custom Renderer of the Entry control since it uses EditText as base for the native control and try to apply all those solutions that I had read previously in it.
Luckly I wasn’t alone on this task and I had help from Nico Milcoff and Federico Maccaroni, thank you guys!

Let’s get down to work!

Note: in order to correctly implement the custom keyboard we are going to need that the Xamarin Forms version to be 3.6.0.135200-pre1 or higher because we need the OnFocusChangeRequest method which is only available from this version.

First we’re going to create the custom control, which will have the next bindable property:

  • EnterCommand : typeof ICommand , to bind Enter key press action.

This is how our custom control will be:

Now we’re moving to our Android project and keep working there (later we will return to our Xamarin Forms project).
Before we go on, ensure to have all the required Android packages:

Next we’re going to edit our Android MainActivity to avoid that native keyboard to show up, for that we will use the SoftInputMode.StateAlwaysHidden attribute

What are we going to do next is start to define our custom keyboard.
Inside the Resource/layout folder we are going to create an Android layout named CustomKeyboard typeof InputMethodService.Keyboard

Firstly we set the alignParentBottom property to true because we want our keyboard to be visible from the bottom side of the screen.
Secondly we set the keyPreviewLayout property to null because on this sample we don’t want a response layout when some key is pressed.
As you can see in the keyBackground property refers to a drawable called keyboard_background, which doesn’t exist yet, so we are going to create it inside the Drawable folder as an xml file, there we are going to define a state selector for the two states our keys can have: normal (without pressing) and pressed.

As you can see, we are going to have to create another two xml inside the Drawable folder, in which we are going to define the look and feel of our keyboard to match (or not) with our application theme.

Now within the values folder we will create an xml named ids which we will need later.

Next, inside the Resources folder we will create a new folder called xml. Within it we will create an xml in which we will define the keys of our special keyboard.
In our case our keyboard will be called special_keyboard, it will be typeof Keyboard in which we will define the horizontal and vertical size of our keys, the horizontalGap and verticalGap properties refer to the spacing and dimension type %p (in case you’ve never seen it) is a kind of percentage relative to the parent view.
Each row of keys will be included within sections delimited by the <Row></Row> tags.
Our first row will be occupied with a separating line to mark the limit of our keyboard. The Row tag will have a height of 4dp and we will indicate that it is at the top of our keyboard through the rowEdgeFlags property. Then we will add a line as a Key within the Row tags that it would take the full width of the keyboard. Our separator is just another xml that we will create inside the Drawable folder:

Each Key will have two strictly necessary properties: codes and keyLabel
code will be a number that tells the OS what letter or symbol the key corresponds to. At this point I want to clarify something: I found dozens of samples about creating customs keyboards for Android and they have used many different codes to refer to a certain symbol or key. The best list of codes that has been fulfilled most of all that I have tried is the following: Android Keycodes. You can also see the official Android docs or even the Xamarin Android but none of them has worked with accuracy.
keyLabel is the string that is going to be shown in our key, it is very important to put this property even if we don’t want to show any text in our key (in that case it would be keyLabel="" ).
For style decision, at the beginning and at the end of each row, I add a Key with code equal to 0 (so you don’t have any action), the width also of 0 and a spacing of 2%p , these keys will also carry the keyEdgeFlags property with the left or right values as appropriate.
Here our full keyboard:

Finally before starting to work in our renderer, we will create another folder within Resources, called anim with an xml that we are going to call slide_in_bottom this will be the animation with which our keyboard will appear on the screen.

Now we will create a new folder on our Android project, named Renderers and there we will create our renderer which we will call EntryWithCustomKeyboardRenderer which will extend from EntryRenderer and implement the interface IOnKeyboardActionListener Also within our custom renderer we will create a private class called NullListener which is going to extend from Java.Lang.Object and implement the interface IOnKeyboardActionListener which we are going to use in our renderer to avoid null exceptions.

Finally, we return to our Xamarin Forms project and implement our special keyboard.

And in our code behind we implement the EnterCommand that we created previously, for the action that we want to happen when we press the Enter key of our custom keyboard.

How can you make a custom keyboard in Android? [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed last year .

The community reviewed whether to reopen this question last year and left it closed:

Original close reason(s) were not resolved

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.

enter image description here

Dog Lover's user avatar

9 Answers 9

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.

enter image description here

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:

    : 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. : It is hard coded here, but you could use something like @dimen/key_height to set it dynamically for different screen sizes. : 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. : 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. : This is the text that is displayed on the key. : This indicates which edge the key should be aligned to. : 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).

  • 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:

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.

    (Android documentation) (source code from Android for a demo custom keyboard) (tutorial) (source code) (tutsplus tutorial) (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 Button s 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 .

First of all you will need a keyboard.xml file which will be placed in the res/xml folder (if the folder does not exist, created it).

**Note that you will have to create the backspace drawable and place it in the res/drawable-ldpi folder with a very small size (like 18×18 pixels)

Then in the xml file that you want it to be used (where your TextView is in) you should add the following code:

**Note that the xml file that you will place the android.inputmethodservice.KeyboardView in, has to be RelativeLayout in order to be able to set the alignParentBottom="true" (Usually the keyboards are presented in the bottom of the screen)

Then you need to add the following code in the onCreate function of the Activity that handles the TextView you want to attach the keyboard to

**Note that mKeyboard and mKeyboardView are private class variables that you have to create.

Then you need the following function for opening the keyboard ( you must associate it with the TextView through the onClick xml property)

And finally you need the OnKeyboardActionListener that will handle your events

Most of the code found here

EDIT:

Since KeyboardView is depreciated since API level 29, you can find its code in this website and create a class in your code before implementing the keyboard as described above.

Pontios's user avatar

In-App Keyboard

This answer tells how to make a custom keyboard to use exclusively within your app. If you want to make a system keyboard that can be used in any app, then see my other answer.

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

enter image description here

1. Start a new Android project

I named my project InAppKeyboard . Call yours whatever you want.

2. Add the layout files

Keyboard layout

Add a layout file to res/layout folder. I called mine keyboard . The keyboard will be a custom compound view that we will inflate from this xml layout file. You can use whatever layout you like to arrange the keys, but I am using a LinearLayout . Note the merge tags.

Activity layout

For demonstration purposes our activity has a single EditText and the keyboard is at the bottom. I called my custom keyboard view MyKeyboard . (We will add this code soon so ignore the error for now.) The benefit of putting all of our keyboard code into a single view is that it makes it easy to reuse in another activity or app.

3. Add the Keyboard Java file

Add a new Java file. I called mine MyKeyboard .

The most important thing to note here is that there is no hard link to any EditText or Activity . This makes it easy to plug it into any app or activity that needs it. This custom keyboard view also uses an InputConnection , which mimics the way a system keyboard communicates with an EditText . This is how we avoid the hard links.

MyKeyboard is a compound view that inflates the view layout we defined above.

4. Point the keyboard to the EditText

For system keyboards, Android uses an InputMethodManager to point the keyboard to the focused EditText . In this example, the activity will take its place by providing the link from the EditText to our custom keyboard to.

Since we aren’t using the system keyboard, we need to disable it to keep it from popping up when we touch the EditText . Second, we need to get the InputConnection from the EditText and give it to our keyboard.

If your Activity has multiple EditTexts, then you will need to write code to pass the right EditText’s InputConnection to the keyboard. (You can do this by adding an OnFocusChangeListener and OnClickListener to the EditTexts. See this article for a discussion of that.) You may also want to hide or show your keyboard at appropriate times.

Finished

That’s it. You should be able to run the example app now and input or delete text as desired. Your next step is to modify everything to fit your own needs. For example, in some of my keyboards I’ve used TextViews rather than Buttons because it is easier to customize them.

Notes

  • In the xml layout file, you could also use a TextView rather a Button if you want to make the keys look better. Then just make the background be a drawable that changes the appearance state when pressed.
  • Advanced custom keyboards: For more flexibility in keyboard appearance and keyboard switching, I am now making custom key views that subclass View and custom keyboards that subclass ViewGroup . The keyboard lays out all the keys programmatically. The keys use an interface to communicate with the keyboard (similar to how fragments communicate with an activity). This is not necessary if you only need a single keyboard layout since the xml layout works fine for that. But if you want to see an example of what I have been working on, check out all the Key* and Keyboard* classes here. Note that I also use a container view there whose function it is to swap keyboards in and out.

now you have kbd which is a normal view.

The nice thing about this is that R.xml.custom refers to /res/xml/custom.xml , which defines in xml the layout of the keyboard. For more information on this file, look here: Keyboard, Keyboard.Row, Keyboard.Key.

Here is a sample project for a soft keyboard.

Your’s should be in the same lines with a different layout.

Edit: If you need the keyboard only in your application, its very simple! Create a linear layout with vertical orientation, and create 3 linear layouts inside it with horizontal orientation. Then place the buttons of each row in each of those horizontal linear layouts, and assign the weight property to the buttons. Use android:layout_weight=1 for all of them, so they get equally spaced.

This will solve. If you didn’t get what was expected, please post the code here, and we are here to help you!

One of the best well-documented example I found.

KeyboardView related XML file and source code are provided.

I came across this post recently when I was trying to decide what method to use to create my own custom keyboard. I found the Android system API to be very limited, so I decided to make my own in-app keyboard. Using Suragch’s answer as the basis for my research, I went on to design my own keyboard component. It’s posted on GitHub with an MIT license. Hopefully this will save somebody else a lot of time and headache.

The architecture is pretty flexible. There is one main view (CustomKeyboardView) that you can inject with whatever keyboard layout and controller you want.

You just have to declare the CustomKeyboardView in you activity xml (you can do it programmatically as well):

Then register your EditText’s with it and tell it what type of keyboard they should use:

The CustomKeyboardView handles the rest!

I’ve got the ball rolling with a Number, NumberDecimal, and QWERTY keyboard. Feel free to download it and create your own layouts and controllers. It looks like this:

Even if this is not the architecture you decide to go with, hopefully it’ll be helpful to see the source code for a working in-app keyboard.

Again, here’s the link to the project: Custom In-App Keyboard

EDIT: I’m no longer an Android developer, and I no longer maintain this GitHub project. There are probably more modern approaches and architectures at this point, but please feel free to reference the GitHub project if you’d like and fork it.

Well Suragch gave the best answer so far but he skipped certain minor stuff that was important to getting the app compiled.

I hope to make a better answer than Suragch by improving on his answer. I will add all the missing elements he didnt put.

I compiled my apk using the android app , APK Builder 1.1.0. So let’s begin.

To build an Android app we need couple files and folders that are organized in a certain format and capitalized accordingly.

res layout -> xml files depicting how app will look on phone. Similar to how html shapes how web page looks on browser. Allowing your app to fit on screens accordingly.

values -> constant data such as colors.xml, strings.xml, styles.xml. These files must be properly spelt.

drawable -> pics; Name them anything.

mipmap -> more pics. used for app icon?

xml -> more xml files.

src -> acts like JavaScript in html. layout files will initiate the starting view and your java file will dynamically control the tag elements and trigger events. Events can also be activated directly in the layout.xml just like in html.

AndroidManifest.xml -> This file registers what your app is about. Application name, Type of program, permissions needed, etc. This seems to make Android rather safe. Programs literally cannot do what they didnt ask for in the Manifest.

Now there are 4 types of Android programs, an activity, a service, a content provider, and a broadcast reciever. Our keyboard will be a service, which allows it to run in the background. It will not appear in the list of apps to launch; but it can be uninstalled.

To compile your app, involves gradle, and apk signing. You can research that one or use APK Builder for android. It is super easy.

Now that we understand Android development, let us create the files and folders.

Create the files and folders as I discussed above. My directory wil look as follows:

  • NumPad
    • AndroidManifest.xml
    • src
      • Saragch
        • num_pad
          • MyInputMethodService.java
          • drawable
            • Suragch_NumPad_icon.png
            • key_preview.xml
            • keyboard_view.xml
            • method.xml
            • number_pad.xml
            • colors.xml
            • strings.xml
            • styles.xml

            Remember if you are using an ide such as Android Studio it may have a project file.

            1. Write files.

            Of course this can be easily edited to your liking. You can even use images instead lf words for the label.

            Suragch didnt demonstrate the files in the values folder and assumed we had access to Android Studio; which automatically creates them. Good thing I have APK Builder.

            This is the file that was really up for contension. Here I felt I would never compile my program. sob. sob. If you check Suracgh’s answer you see he leaves the first set of fields empty, and adds the activity tag in this file. As I said there are four types of Android programs. An activity is a regular app with a launcher icon. This numpad is not an activity! Further he didnt implement any activity.

            My friends do not include the activity tag. Your program will compile, and when you try to launch it will crash! As for xmlns:android and uses-sdk; I cant help you there. Just try my settings if they work.

            As you can see there is a service tag, which register it as a service. Also service.android:name must be name of public class extending service in our java file. It MUST be capitalized accordingly. Also package is the name of the package we declared in java file.

            Note: I think java is an alternative to src.

            This was another problem file but not as contentious as the manifest file. As I know Java good enough to know what is what, what is not. I barely know xml and how it ties in with Android development!

            The problem here was he didnt import anything! I mean, he gave us a «complete» file which uses names that couldnt be resolved! InputMethodService, Keyboard, etc. That is bad practice Mr. Suragch. Thanks for helping me out but how did you expect the code to compile if the names cant be resolved?

            Following is the correctly edited version. I just happened to pounce upon couple hints to drove me to the right place to learn what exactly to import.

            Compile and sign your project.

            This is where I am clueless as a newby Android developer. I would like to learn it manually, as I believe real programmers can compile manually.

            I think gradle is one of the tools for compiling and packaging to apk. apk seems to be like a jar file or a rar for zip file. There are then two types of signing. debug key which is not alllowed on play store and private key.

            Well lets give Mr. Saragch a hand. And thank you for watching my video. Like, subscribe.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *