如何在 Android 中制作自定义键盘? [英] How can you make a custom keyboard in Android?
问题描述
我想做一个自定义键盘.我不知道如何使用 XML 和 Java 来做到这一点.下图是我想做的键盘模型.它只需要数字.
系统键盘
此答案说明如何制作可在用户安装在手机上的任何应用程序中使用的自定义系统键盘.如果您想制作仅在您自己的应用中使用的键盘,请
以下步骤显示了如何创建可工作的自定义系统键盘.我尽可能地尝试删除任何不必要的代码.如果您还需要其他功能,我在最后提供了更多帮助的链接.
1.启动一个新的 Android 项目
我将我的项目命名为自定义键盘".随心所欲地称呼它.这里没有什么特别的.我将离开 MainActivity
和Hello World!"布局原样.
2.添加布局文件
将以下两个文件添加到您应用的 res/layout
文件夹中:
- keyboard_view.xml
- key_preview.xml
keyboard_view.xml
这个视图就像一个容器,可以容纳我们的键盘.在这个例子中只有一个键盘,但你可以添加其他键盘并将它们交换进出这个 KeyboardView
.
</android.inputmethodservice.KeyboardView>
key_preview.xml
按键预览是当您按下键盘按键时弹出的布局.它只显示您按下的键(以防您的大而肥的手指覆盖它).这不是一个多选弹出窗口.为此,您应该查看候选人视图.
</TextView>
3.添加支持的xml文件
在您的 res
文件夹中创建一个 xml
文件夹.(右键单击res
并选择新建> 目录.)
然后在其中添加以下两个xml文件.(右键单击xml
文件夹并选择新建> XML 资源文件.)
- number_pad.xml
- 方法.xml
number_pad.xml
这是它开始变得更有趣的地方.这个 Keyboard
定义了 Keyboard
的布局a href="https://developer.android.com/reference/android/inputmethodservice/Keyboard.Key.html" rel="noreferrer">键.
<行><Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"/><Key android:codes="50" android:keyLabel="2"/><Key android:codes="51" android:keyLabel="3"/><Key android:codes="52" android:keyLabel="4"/><Key android:codes="53" android:keyLabel="5" android:keyEdgeFlags="right"/></行><行><Key android:codes="54" android:keyLabel="6" android:keyEdgeFlags="left"/><Key android:codes="55" android:keyLabel="7"/><Key android:codes="56" android:keyLabel="8"/><Key android:codes="57" android:keyLabel="9"/><Key android:codes="48" android:keyLabel="0" android:keyEdgeFlags="right"/></行><行><Key android:codes="-5"机器人:keyLabel =删除"android:keyWidth="40%p"机器人:keyEdgeFlags =左"android:isRepeatable="true"/><Key android:codes="10"android:keyLabel="回车"android:keyWidth="60%p"android:keyEdgeFlags="right"/></行></键盘>
需要注意以下几点:
keyWidth
:这是每个键的默认宽度.20%p
表示每个键应占据 p 区域宽度的 20%.但是,它可以被单个键覆盖,正如您在第三行中使用 Delete 和 Enter 键所看到的那样.keyHeight
:这里是硬编码的,但你可以使用类似@dimen/key_height
的东西来为不同的屏幕尺寸动态设置它.差距
:水平和垂直间隙表示键之间留有多少空间.即使你把它设置为0px
仍然有一个小的差距.codes
:这可以是 Unicode 或自定义代码值,用于确定按下键时会发生什么或输入什么.请参阅keyOutputText
如果要输入更长的 Unicode 字符串.keyLabel
:这是键上显示的文本.keyEdgeFlags
:这表示键应该对齐到哪条边.isRepeatable
:如果你按住键,它会不断重复输入.
method.xml
这个文件告诉系统可用的输入法子类型.我只是在这里包含了一个最小版本.
<亚型android:imeSubtypeMode="键盘"/></输入法>
4.添加处理按键输入的Java代码
创建一个新的 Java 文件.我们称之为MyInputMethodService
.该文件将所有内容联系在一起.它处理从键盘接收到的输入并将其发送到接收它的任何视图(例如,EditText
).
public class MyInputMethodService extends InputMethodService 实现 KeyboardView.OnKeyboardActionListener {@覆盖公共视图 onCreateInputView() {//获取 KeyboardView 并将我们的键盘布局添加到它KeyboardView keyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view, null);键盘键盘=新键盘(这个,R.xml.number_pad);键盘视图.setKeyboard(键盘);keyboardView.setOnKeyboardActionListener(this);返回键盘视图;}@覆盖public void onKey(int primaryCode, int[] keyCodes) {InputConnection ic = getCurrentInputConnection();如果(ic == null)返回;开关(主代码){案例键盘.KEYCODE_DELETE:CharSequence selectedText = ic.getSelectedText(0);如果(TextUtils.isEmpty(selectedText)){//没有选择,所以删除前一个字符ic.deleteSurroundingText(1, 0);} 别的 {//删除选择ic.commitText("", 1);}休息;默认:字符代码=(字符)primaryCode;ic.commitText(String.valueOf(code), 1);}}@覆盖public void onPress(int primaryCode) { }@覆盖public void onRelease(int primaryCode) { }@覆盖public void onText(CharSequence text) { }@覆盖公共无效 swipeLeft() { }@覆盖公共无效 swipeRight() { }@覆盖公共无效滑动(){}@覆盖公共无效 swipeUp() { }}
注意事项:
OnKeyboardActionListener
监听键盘输入.在此示例中,它还需要所有这些空方法.InputConnection
用于将输入发送到另一个视图,例如EditText
.
5.更新清单
我把它放在最后而不是放在第一位,因为它指的是我们上面已经添加的文件.要将您的自定义键盘注册为系统键盘,您需要添加一个 service
部分添加到您的 AndroidManifest.xml 文件中.把它放在 activity
之后的 application
部分.
<应用... ><活动... >...</活动><服务android:name=".MyInputMethodService"android:label="键盘显示名称"android:permission="android.permission.BIND_INPUT_METHOD"><意图过滤器><action android:name="android.view.InputMethod"/></意图过滤器><元数据android:name="android.view.im"android:resource="@xml/方法"/></服务></应用程序></清单>
就是这样!您现在应该可以运行您的应用了.但是,除非您在设置中启用键盘,否则您将看不到太多内容.
6.在设置中启用键盘
每个想要使用您的键盘的用户都必须在 Android 设置中启用它.有关如何执行此操作的详细说明,请参阅以下链接:
总结如下:
- 转到 Android 设置 > 语言和输入 > 当前键盘 > 选择键盘.
- 您应该会在列表中看到您的自定义键盘.启用它.
- 返回并再次选择当前键盘.您应该会在列表中看到您的自定义键盘.选择它.
现在,您应该可以在任何可以在 Android 中输入的地方使用键盘了.
进一步研究
上面的键盘是可用的,但要创建其他人想要使用的键盘,您可能需要添加更多功能.研究以下链接以了解方法.
- 创建输入法(Android 文档)
- SoftKeyboard(来自 Android 的源代码,用于演示自定义键盘)
- 构建自定义 Android 键盘(教程)(源代码)
- 在 Android 上创建自定义键盘(tutsplus 教程)
- 如何为安卓创建自定义键盘(YouTube 视频:无声但关注沿着是我第一次学会如何做到这一点.)
继续
不喜欢标准 KeyboardView
的外观和行为?我当然不会.看起来它自 Android 2.0 以来就没有更新过.Play 商店中的所有自定义键盘怎么样?它们看起来不像上面丑陋的键盘.
好消息是您可以完全自定义自己的键盘外观和行为.您需要执行以下操作:
- 创建您自己的自定义键盘视图,子类化
ViewGroup
.您可以使用Button
填充它,甚至可以创建自己的自定义键视图,子类View
.如果您使用弹出式视图,请注意这一点. - 在键盘中添加自定义事件侦听器界面.为诸如
onKeyClicked(String text)
或onBackspace()
之类的东西调用它的方法. - 您不需要添加上述说明中描述的
keyboard_view.xml
、key_preview.xml
或number_pad.xml
,因为这些都是标准的KeyboardView
.您将在自定义视图中处理所有这些 UI 方面. - 在您的
MyInputMethodService
类中,实现您在键盘类中定义的自定义键盘侦听器.它代替了不再需要的KeyboardView.OnKeyboardActionListener
. - 在您的
MyInputMethodService
类的onCreateInputView()
方法中,创建并返回自定义键盘的实例.不要忘记将键盘的自定义侦听器设置为this
.
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.
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
.
<?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/keyboard_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:keyPreviewLayout="@layout/key_preview"
android:layout_alignParentBottom="true">
</android.inputmethodservice.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.
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@android:color/white"
android:textColor="@android:color/black"
android:textSize="30sp">
</TextView>
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.
<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:keyWidth="20%p"
android:horizontalGap="5dp"
android:verticalGap="5dp"
android:keyHeight="60dp">
<Row>
<Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"/>
<Key android:codes="50" android:keyLabel="2"/>
<Key android:codes="51" android:keyLabel="3"/>
<Key android:codes="52" android:keyLabel="4"/>
<Key android:codes="53" android:keyLabel="5" android:keyEdgeFlags="right"/>
</Row>
<Row>
<Key android:codes="54" android:keyLabel="6" android:keyEdgeFlags="left"/>
<Key android:codes="55" android:keyLabel="7"/>
<Key android:codes="56" android:keyLabel="8"/>
<Key android:codes="57" android:keyLabel="9"/>
<Key android:codes="48" android:keyLabel="0" android:keyEdgeFlags="right"/>
</Row>
<Row>
<Key android:codes="-5"
android:keyLabel="DELETE"
android:keyWidth="40%p"
android:keyEdgeFlags="left"
android:isRepeatable="true"/>
<Key android:codes="10"
android:keyLabel="ENTER"
android:keyWidth="60%p"
android:keyEdgeFlags="right"/>
</Row>
</Keyboard>
Here are some things to note:
keyWidth
: This is the default width of each key. The20%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 to0px
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. SeekeyOutputText
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.
<?xml version="1.0" encoding="utf-8"?>
<input-method
xmlns:android="http://schemas.android.com/apk/res/android">
<subtype
android:imeSubtypeMode="keyboard"/>
</input-method>
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 anEditText
.
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
.
<manifest ...>
<application ... >
<activity ... >
...
</activity>
<service
android:name=".MyInputMethodService"
android:label="Keyboard Display Name"
android:permission="android.permission.BIND_INPUT_METHOD">
<intent-filter>
<action android:name="android.view.InputMethod"/>
</intent-filter>
<meta-data
android:name="android.view.im"
android:resource="@xml/method"/>
</service>
</application>
</manifest>
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.
- 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:
- Create your own custom keyboard view that subclasses
ViewGroup
. You could fill it withButton
s or even make your own custom key views that subclassView
. If you use popup views, then note this. - Add a custom event listener interface in your keyboard. Call its methods for things like
onKeyClicked(String text)
oronBackspace()
. - You don't need to add the
keyboard_view.xml
,key_preview.xml
, ornumber_pad.xml
described in the directions above since these are all for the standardKeyboardView
. You will handle all these UI aspects in your custom view. - In your
MyInputMethodService
class, implement the custom keyboard listener that you defined in your keyboard class. This is in place ofKeyboardView.OnKeyboardActionListener
, which is no longer needed. - In your
MyInputMethodService
class'sonCreateInputView()
method, create and return an instance of your custom keyboard. Don't forget to set the keyboard's custom listener tothis
.
这篇关于如何在 Android 中制作自定义键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!