Search code examples
javascriptsafarilit

Moving the contents of the page up when mobile keyboard is shown


How do I move the contents of the page up when the mobile keyboard is shown? Right now on Safari in IOS native, when the mobile keyboard is shown, the keyboard covers the input box. I need to make sure it doesn't cover the input box.


Solution

  • In Android if you are using native webview there is simply No WAY to move content up to show Input Field. One hack to achieve this is to calculate your views height and add Padding to bottom like this:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // Call to monitor state od keyboard
        Handler(Looper.getMainLooper()).postDelayed({ monitorKeyboardState() },500)
    }
    
    
    private fun monitorKeyboardState() {
        pActivity?.let {
    
            //Getting  Status bar height
            val statusBarHeightInPx = dpToPx((it.statusBarHeight))
    
            //Getting  Tool bar height
            val toolBarHeight = binding.webViewToolbar.height
            binding.webViewMainLayout.let {
                it.viewTreeObserver.addOnGlobalLayoutListener {
    
                    val r = Rect()
                    it.getWindowVisibleDisplayFrame(r)
    
                    //Calculating Differences
    
                    val heightDiff =
                        it.rootView.height - r.height() - statusBarHeightInPx - toolBarHeight
    
                    //Adding padding bottom
                    Handler(Looper.getMainLooper()).post {
                        it.setPadding(
                            0,
                            0,
                            0,
                            heightDiff.toInt()
                        )
                    }
                }
            }
        }
    }
    
    
    private fun dpToPx(valueInDp: Float): Float {
        val metrics: DisplayMetrics? = context?.resources?.displayMetrics
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics)
    }