Skip to content

Instantly share code, notes, and snippets.

@enricocid
Last active December 29, 2019 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enricocid/ce4a0b0ac9420bdec558e57c341417ed to your computer and use it in GitHub Desktop.
Save enricocid/ce4a0b0ac9420bdec558e57c341417ed to your computer and use it in GitHub Desktop.
[Android/Kotlin] Center TextView in custom Toolbar when Navigation Icon is present
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//get the toolbar
val toolbar = (get your toolbar)
setSupportActionBar(toolbar)
//enable navigation icon
supportActionBar?.apply {
setDisplayShowHomeEnabled(true)
setDisplayHomeAsUpEnabled(true)
}
//you can measure the "minumum inset for content views within a bar
//when a navigation button is present, such us an up button"
toolbar.afterMeasured {
//set this value as padding end to the TextView
yourCenteredTextView.setPadding(0, 0, toolbar.contentInsetStartWithNavigation, 0)
}
}
//Generified function to measure layout params
//https://antonioleiva.com/kotlin-ongloballayoutlistener/
private inline fun <T : View> T.afterMeasured(crossinline f: T.() -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (measuredWidth > 0 && measuredHeight > 0) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
f()
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment