我找到了一种使用状态栏大小的解决方案,它应该适合任何设备。这是一种将大小从代码转换为 XML 布局的方法。
解决方案是创建一个根据状态栏大小自动调整大小的视图。它就像约束布局的指南。
我确信它应该是一个更好的方法,但我没有找到它。如果您考虑改进此代码,请现在告诉我:
科特林
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
}
}
那么你可以在 XML 中使用它作为指南:
<com.foo.StatusBarSizeView
android:id="@+id/fooBarSizeView"
android:layout_width="match_parent"
android:layout_height="0dp" />
“heightSize”变量是公开的,如果某些视图需要它,可以在代码中使用它。
也许它对其他人有帮助。