Last active
December 29, 2019 12:50
-
-
Save enricocid/ce4a0b0ac9420bdec558e57c341417ed to your computer and use it in GitHub Desktop.
[Android/Kotlin] Center TextView in custom Toolbar when Navigation Icon is present
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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