'Android: Adding custom keyboard on screen

My goal: A custom keyboard that can be added as a view (meaning, the aim is not to use the Android system keyboard at all) programmatically on the screen, just like a button, etc.

What I have done so far: I have created the layout file for the keyboard with all its buttons and so on. Also created a Kotlin class which can be called to render the keyboard in the current fragment.

Custom keyboard class:

class CustomKeyboard(context: Context, layout: String = "en") : ConstraintLayout(context){
    fun createLayout() {
        val inflater = LayoutInflater.from(context)
        val keyboardView = inflater.inflate(R.layout.keyboard, this, false)
        addView(keyboardView)
    }
}

And here I call the class in my fragment to render the keyboard:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        fun showKeyboard() {
            val keyboard = CustomKeyboard(requireContext(), "en")
            keyboard.createLayout()
            binding.root.addView(keyboard)

        }
        showKeyboard()
        // ... Other class code here

My issue: The keyboard renders correctly, but it is positioned in the top-left corner of the screen. In the layout file for the keyboard, I'm using a constraint layout which specifies where the keyboard should be positioned on the screen (horizontal center and bottom of the screen).

How can I position the keyboard correctly in the fragment, and is this even a proper way of achieving the goal?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source