1

这个问题是这个#3的一部分

有些 Chromebook 是笔记本电脑,我们也可以将其转换为平板电脑模式。从这里查看图片

所以我的问题是如何以编程方式检测 Chromebook 的模式(笔记本电脑或平板电脑)。为此,我这样做了,但这仅适用于Lenovo Flex11,在其他 Chromebook 中不起作用

context.getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES;

如果此条件返回 true,则表示 Chromebook 处于平板电脑模式,否则处于笔记本电脑模式

我需要检查这一点,因为如果 Chromebook 处于笔记本电脑模式,那么我必须仅在特定活动中显示预测栏。如果它处于平板模式,则会出现软键盘,并且预测栏由候选视图管理InputMethodService

4

1 回答 1

1

我们使用两种不同事物的组合。首先是我们使用以下代码片段检测设备是否处于桌面模式:

fun isDesktopMode() : Boolean {
   var hasMouse = false
   val hasKeyboard = resources.configuration.keyboard == KEYBOARD_QWERTY
   val isKeyboardUseable = resources.configuration.hardKeyboardHidden == HARDKEYBOARDHIDDEN_NO

   // Check each input device to see if it is a mouse
   val inputManager = getSystemService(Context.INPUT_SERVICE) as InputManager
   for (deviceId in inputManager.inputDeviceIds) {
       val sourceMask = inputManager.getInputDevice(deviceId).sources
       if ((sourceMask or SOURCE_MOUSE == sourceMask) ||
           (sourceMask or SOURCE_TOUCHPAD == sourceMask) ||
           (sourceMask or SOURCE_TRACKBALL == sourceMask)) {
               hasMouse = true
       }
   }

   return hasMouse && hasKeyboard && isKeyboardUseable
}

为了检测键盘是否已插入和/或可用,我们使用以下侦听器来侦听键盘是否已激活:

val inputManager = getSystemService(Context.INPUT_SERVICE) as InputManager
val inputDeviceListener = object: InputManager.InputDeviceListener {
   override fun onInputDeviceRemoved(deviceId: Int) {
       // Be careful checking device here as it is no longer attached to the system
   }

   override fun onInputDeviceAdded(deviceId: Int) {
       // If you want to learn more about what has been attached, check the InputDevice
       // using the id.
       val sourceMask = inputManager.getInputDevice(deviceId).sources
       if (sourceMask or SOURCE_KEYBOARD == sourceMask) {
           //Keyboard has been Added
           append_to_log("A keyboard has been added.")
       }
   }

   override fun onInputDeviceChanged(deviceId: Int) {
       // Best practice is to check for what you care about when things change (ie. are
       // there any keyboards/mice still attached and usable. Users may have multiple
       // devices attached (integrated keyboard a and bluetooth keyboard) and
       // removing one does not mean the other is no longer available.
       isInDesktopMode = isDesktopMode()
   }
}
inputManager.registerInputDeviceListener(inputDeviceListener, null)

这篇文章在 Apache 2.0 下获得许可。

https://developers.google.com/open-source/devplat

于 2021-01-20T15:07:24.837 回答