Skip to content

Instantly share code, notes, and snippets.

@happysingh23828
Last active September 4, 2020 06:39
Show Gist options
  • Save happysingh23828/e028afae3651bea4e57888db1bd47cbc to your computer and use it in GitHub Desktop.
Save happysingh23828/e028afae3651bea4e57888db1bd47cbc to your computer and use it in GitHub Desktop.
set view height when show soft keyboard is open
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mView = inflater.inflate(R.layout.fragment_base_section, container, false)
KeyboardUtil(requireActivity(), mView.coordinatorLayout)
return mView
}
import android.app.Activity
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver
import android.view.inputmethod.InputMethodManager
class KeyboardUtil(act: Activity, private val contentView: View) {
private val decorView: View = act.window.decorView
private var negativeHeight = 0
//a small helper to allow showing the editText focus
private var onGlobalLayoutListener: ViewTreeObserver.OnGlobalLayoutListener =
ViewTreeObserver.OnGlobalLayoutListener {
val r = Rect()
//r will be populated with the coordinates of your view that area still visible.
decorView.getWindowVisibleDisplayFrame(r)
//get screen height and calculate the difference with the useable area from the r
val height = decorView.context.resources.displayMetrics.heightPixels
val diff = height - r.bottom
//if it could be a keyboard add the padding to the view
if (diff != 0) {
// if the use-able screen height differs from the total screen height we assume that it shows a keyboard now
//check if the padding is 0 (if yes set the padding for the keyboard)
if (contentView.paddingBottom != diff) {
if(negativeHeight==0 && diff<0){
negativeHeight = -(diff)
}
contentView.setPadding(0, 0, 0, diff+negativeHeight)
//set the padding of the contentView for the keyboard
}
} else {
negativeHeight = 0
//check if the padding is != 0 (if yes reset the padding)
if (contentView.paddingBottom != 0) {
//reset the padding of the contentView
contentView.setPadding(0, 0, 0, 0)
}
}
}
init {
//only required on newer android versions. it was working on API level 19
decorView.viewTreeObserver.addOnGlobalLayoutListener(onGlobalLayoutListener)
}
companion object {
/**
* Helper to hide the keyboard
*
* @param act
*/
fun hideKeyboard(act: Activity?) {
if (act != null && act.currentFocus != null) {
val inputMethodManager = act.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(act.currentFocus!!.windowToken, 0)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment