【问题标题】:Styling attributes not functioning on merge tags样式属性在合并标签上不起作用
【发布时间】:2014-08-30 15:47:34
【问题描述】:

背景

我发现样式属性在 merge 标签上不起作用,要么单独应用属性,要么应用样式。

已知解决方案

  1. 在标签上应用样式属性以利用布局作品。例如,包含标签和自定义标签。

  2. 只是不要使用合并。

  3. 以编程方式应用样式。

但是,我正在寻找更好的解决方案。

为什么?

  1. 很乱。每次使用布局时,我都必须应用样式属性。我把它做成一个单独的布局,因为它们是为了重复使用。

  2. 我有意使用 merge 标签,因为它们必须是父布局的直接子级。例如,标签是 LinearLayout 的子级。我应用 layout_width="0dp"layout_weight="1" 让它们在父布局中均匀分布。

  3. 原因 #2 加上标签是以编程方式生成的。因此,我只能以编程方式应用样式。很难看,需要额外的维护工作。

目标

令人满意的解决方法。

用于插图目的的 XML 标签

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/CustomStyle">
    <!-- Omitted -->
</merge>

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1">
    <!-- Omitted -->
</merge>

以上两个标签都没有样式。

【问题讨论】:

    标签: android android-layout android-view android-xml android-styles


    【解决方案1】:

    合并标签中的属性被忽略。当 XML 解析器看到一个合并标签时,它会告诉它,“跳过这个标签并直接添加所有子标签。”

    【讨论】:

    • 如果要向其添加属性,请使用 FrameLayout 而不是合并标签。
    【解决方案2】:

    我已经坐在这个小东西上一段时间了,所以我想我会分享一下。

    这很简单,你指定你正在使用的布局。它将解析 xml 及其属性,然后将其提供给构造函数。

    fun Context.defaultAttr(@LayoutRes resource: Int): AttributeSet {
        val parser = resources.getLayout(resource)
        return Xml.asAttributeSet(parser)
    }
    

    用法如下:

    class MyCustomView(
        context: Context,
        attrs: AttributeSet? = context.defaultAttr(R.layout.view_mycustom),
        defStyleAttr: Int = 0
    ) : ConstraintLayout(context, attrs, defStyleAttr) {
        
            val binding: ViewHabitBinding = ViewMyCustomBinding.inflate(LayoutInflater.from(context), this)
    
            // Your implementation of MyCustom view.
        }
    

    我根本没有研究过它的性能,但它基本上可以解析 XML 并获取你的属性,所以我认为它不是完全免费的。但我认为让视图尽可能干净和可读是一种权衡。

    【讨论】:

      猜你喜欢
      • 2013-10-21
      • 1970-01-01
      • 2018-02-06
      • 2023-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      相关资源
      最近更新 更多