【问题标题】:margin does not apply for view API 22保证金不适用于视图 API 22
【发布时间】:2020-04-06 02:09:04
【问题描述】:

我需要到视图的边缘。我正在通过

以编程方式进行操作
view.layoutParams = LayoutParams(size, size).apply {
                    topMargin = resources.getDimensionPixelOffset(R.dimen._4sdp)
                }

但是,当我在 API 22 上测试布局时,边距不适用,但在 API 28 中一切正常。

【问题讨论】:

标签: android android-layout margins


【解决方案1】:

这就是我想在 Kotlin 中做的方式 -

fun View.margin(left: Float? = null, top: Float? = null, right: Float? = null, bottom: Float? = null) {
    layoutParams<ViewGroup.MarginLayoutParams> {
        left?.run { leftMargin = dpToPx(this) }
        top?.run { topMargin = dpToPx(this) }
        right?.run { rightMargin = dpToPx(this) }
        bottom?.run { bottomMargin = dpToPx(this) }
    }
}

inline fun <reified T : ViewGroup.LayoutParams> View.layoutParams(block: T.() -> Unit) {
    if (layoutParams is T) block(layoutParams as T)
}

fun View.dpToPx(dp: Float): Int = context.dpToPx(dp)
fun Context.dpToPx(dp: Float): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics).toInt()

现在我们只需要在这样的视图上调用它

textView.margin(left = 16F)

【讨论】:

  • 不幸的是,它没有帮助。边距为 0。我在 API 22/23 中测试出现问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-30
相关资源
最近更新 更多