我正在使用InputMethodService,Keyboard和KeyboardView(我知道,最近已弃用)以创建自定义键盘。
override fun onCreateInputView(): View {
view = layoutInflater.inflate(
R.layout.keyboard_view_test,
null
)
keyboardView =
view.findViewById<KeyboardView>(R.id.keyboard)
keyboard = Keyboard(this, R.xml.keyboard_layout)
keyboardView.keyboard = keyboard
keyboardView.isPreviewEnabled = false
keyboardView.setOnKeyboardActionListener(this)
return keyboardView
}
当将keyboard_view_test.xml中的KeyboardView用作根元素时,键盘可以正常工作。当我开始将其包装在LinearLayout或任何其他ViewGroup中而不更改任何其他内容时(请参阅keyboard_view_test.xml),我得到了IllegalStateException。我不明白,stacktrace没有引用我的任何代码。我该如何运作?
keyboard_view_test.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorGboardBackground">
<android.inputmethodservice.KeyboardView
android:id="@+id/keyboard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorGboardBackground"
android:keyBackground="@drawable/key_background"
android:keyPreviewLayout="@layout/key_preview"
android:keyPreviewOffset="10dp"
android:keyTextColor="@color/colorGboardKeyText"
android:keyTextSize="22sp"
android:labelTextSize="22sp"
android:shadowRadius="0" />
该错误似乎在onCreateInputView()返回之后立即发生
错误堆栈:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:5038)
at android.view.ViewGroup.addView(ViewGroup.java:4869)
at android.view.ViewGroup.addView(ViewGroup.java:4841)
at android.inputmethodservice.InputMethodService.setInputView(InputMethodService.java:1596)
at android.inputmethodservice.InputMethodService.updateInputViewShown(InputMethodService.java:1431)
at android.inputmethodservice.InputMethodService.showWindowInner(InputMethodService.java:1835)
at android.inputmethodservice.InputMethodService.showWindow(InputMethodService.java:1803)
at android.inputmethodservice.InputMethodService$InputMethodImpl.showSoftInput(InputMethodService.java:570)
at android.inputmethodservice.IInputMethodWrapper.executeMessage(IInputMethodWrapper.java:207)
at com.android.internal.os.HandlerCaller$MyHandler.handleMessage(HandlerCaller.java:37)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
最佳答案
正如@Ben P.指出的,我显然必须将return keyboardView
更改为return view
。起初我忽略了它。