I have found a solution to work with status bar size that should be fit to any device. It is a way to transform the size from code to XML layouts.
The solution is to create a view that is auto-sized with the status bar size. It is like a guide from constraint layout.
I am sure it should be a better method but I didn't find it. And if you consider something to improve this code please let me now:
KOTLIN
class StatusBarSizeView: View {
companion object {
// status bar saved size
var heightSize: Int = 0
}
constructor(context: Context):
super(context) {
this.init()
}
constructor(context: Context, attrs: AttributeSet?):
super(context, attrs) {
this.init()
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int):
super(context, attrs, defStyleAttr) {
this.init()
}
private fun init() {
// do nothing if we already have the size
if (heightSize != 0) {
return
}
// listen to get the height
(context as? Activity)?.window?.decorView?.setOnApplyWindowInsetsListener { _, windowInsets ->
// get the size
heightSize = windowInsets.systemWindowInsetTop
// return insets
windowInsets
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
// if height is not zero height is ok
if (h != 0 || heightSize == 0) {
return
}
// apply the size
postDelayed(Runnable {
applyHeight(heightSize)
}, 0)
}
private fun applyHeight(height: Int) {
// apply the status bar height to the height of the view
val lp = this.layoutParams
lp.height = height
this.layoutParams = lp
}
}
Then you can use it in XML as a guide:
<com.foo.StatusBarSizeView
android:id="@+id/fooBarSizeView"
android:layout_width="match_parent"
android:layout_height="0dp" />
The "heightSize" variable is public to can use it in the code if some view need it.
Maybe it helps to someone else.