风格

2017-04-14 75 views
1

定义安口忽略layout_margin我创建了一个自定义样式:风格

<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值被忽略。

如果我在安口手动添加保证金:

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

保证金是好的。

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

回答

3

这不是安口的问题,这就是Android是如何工作的:

如果在自定义样式指定layout_margin,这种风格必须明确地应用到您希望所指定的空白每一个人观点(如下面的代码示例所示)。将此样式包含在主题中并将其应用于您的应用程序或活动将不起作用。

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

请看here了解更多。

1

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

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

解决办法:

我想限定matchParent宽度和高度和16DP的用于TableView中的裕度,所以我创建延伸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) } 

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

+1

谢谢主席先生!你现在是我的个人英雄! :) – Antek