1

我创建了一个自定义样式:

<style name="Static">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_marginEnd">5dp</item>
</style>

然后我用静态函数扩展了anko:

inline fun ViewManager.static(theme: Int = R.style.Static, init: TextView.() -> Unit) = ankoView(::TextView, theme, init)

当我在布局中使用它时:

static { text = resources.getString(R.string.name) }

marginEnd 值被忽略。

如果我在 anko 中手动添加边距:

static { text = resources.getString(R.string.name) }.lparams { marginEnd = dip(5) }

边距很好。

你们知道anko忽略了我的边距值或任何其他方式为扩展视图anko函数定义预定义边距的情况吗?

4

2 回答 2

3

这不是 Anko 的问题,这是 Android 的工作原理:

如果您在自定义样式中指定 layout_margin,则必须将此样式显式应用于您希望具有指定边距的每个单独的视图(如下面的代码示例所示)。在主题中包含此样式并将其应用于您的应用程序或活动将不起作用。

这是因为以 layout_ 开头的属性是LayoutParams,或者在本例中是MarginLayoutParams. 每个ViewGroup都有自己的LayoutParams 实现。因此layout_margin,不仅仅是可以在任何地方应用的通用属性。它必须在ViewGroup明确将其定义为有效参数的 a 的上下文中应用。

在这里查看更多信息。

于 2017-04-14T10:22:09.890 回答
1

正如@John 在他的回答中指出的那样,使用样式不是定义布局参数的选项。

因此,我开发了一个在 applyRecursively 中使用的函数,它遍历视图并应用我想要应用的布局。

解决方案:

我想为 TableView 定义宽度和高度的 matchParent 以及 16dp 的边距,所以我创建了一个扩展 TableLayout 的新类

class TableViewFrame(context: Context) : TableLayout(context)

然后在视图是 TableViewFrame 的函数中应用我的布局

fun applyTemplateViewLayouts(view: View) {
    when(view) {
        is TableViewFrame -> {
            when(view.layoutParams) {
                is LinearLayout.LayoutParams -> {
                    view.layoutParams.height = matchParent
                    view.layoutParams.width = matchParent
                    (view.layoutParams as LinearLayout.LayoutParams).margin = view.dip(16)
                }
            }
        }
    }
}

要使用该函数,在视图定义中,我只需将其传递给 applyRecursively:

verticalLayout {
        tableViewFrame {
            tableRow {
                ...
            }
        }
    }
}.applyRecursively { view -> applyTemplateViewLayouts(view) }

我在 medium 上写了一篇文章,有更详细的解释:https ://medium.com/@jonathanrafaelzanella/using-android-styles-with-anko-e3d5341dd5b4

于 2017-04-14T22:33:59.980 回答