我们可以将标签分配给 <include> 语句吗

Can we assign a tag to an <include> statement

我正在从一个笨拙的视图布局(有很多重复的基本视图组)过渡到一个每个类型的视图组都有自己的布局,然后我将其包含在每个布局中的布局。

每个视图组都有一个带有特定视图 ID(使用 @+id/...)的控件元素(例如复选框),以及一个关联的文本视图(标签),它引用一个字符串 ID(使用 @string/...).

到目前为止,最简单(也是最没有错误)的转换方式(至少在第一阶段)是使用搜索(使用正则表达式)并用包含替换视图组,但是由于每个视图组有两个不同的信息位(视图 ID 和字符串 ID),我需要将其替换为包含这两个信息位的包含,以便我可以以编程方式将视图放回原处并将正确的文本分配给文本视图。

计划以这样的方式结束:

<include layout="@layout/setting_switch"
    android:tag="some_string_name"
    android:id="@+id/some_view_group" />

在上面,标签 some_string_name 可用于为包含的布局中的文本视图获取正确的字符串,id some_view_group 可用于在包括使用两级 findViewById(R.id.some_view_group).findViewById(R.id.generic_switch).

的布局

但似乎 findViewById(R.id.some_view_group).getTag()(我想用它来获取具有该名称的字符串)returns null.

有什么方法可以直接在 XML 中指定诸如标签之类的内容以使我的计划生效吗?

(顺便说一句,lint 并没有抱怨我在上面使用了 android:tag,这让我一开始觉得它可能没问题......也许我只是没有使用正确的方法来阅读标签回来了?)

我认为您无法如愿将标签属性的值转移到包含的布局中。参见 Use the <include> tag

You can also override all the layout parameters (any android:layout_* attributes) of the included layout's root view by specifying them in the tag.

标记参数的类型不正确,无法传输。

无论如何,Compound Control will be a better option. It is a standard type of implementation which will be more maintainable than the tag option you are looking at and will do all the things you want and more. With a compound control, it is easy to over nest view groups. Take a look also at the merge tag.