Android 上的 ?attr/ 是什么意思?
What does ?attr/ mean on Android?
我正在处理一个关于支持库和工具栏的示例,这是 Android 文档
上的布局代码
<android.support.v7.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
这是我第一次看到这些 ?attr
,我不知道它们是什么意思,也不知道这些值存储在哪里。这些是自定义的还是在 Android 框架上预定义的?
?attr/
对属性的引用。属性是应用程序主题中指定的值。您示例中的属性都是支持库提供的主题中指定的所有值。 Android 也有自己的属性,可以与 ?android:attr/
一起使用。
最终要使用的实际值取决于用于扩充所述布局的主题。这个主题可以在应用范围主题的 <application/>
块中的清单中指定,或者在特定 activity 的 <activity/>
块中指定。您还可以在运行时使用不同的上下文覆盖此主题(参见 ContextThemeWrapper and LayoutInflater)
在布局中使用主题属性而不是硬编码值被认为是一种很好的做法,因为它可以轻松自定义。例如,当您创建自定义视图时,您可以使用 ?attr/colorAccent
这样视图的用户不必提供颜色,它将使用应用程序主题中使用的 colorAccent
反而。
这在今天变得更加重要,因为在 Android Q 中引入了深色主题,您的布局应该指定一个属性,以便在使用浅色主题和深色主题时最终值不同。
A style attribute resource allows you to reference the value of an
attribute in the currently-applied theme.
Rather than setting a static color (#ffffff
or a @color
resource)
we can delegate to the theme by using the ?attr/themeAttributeName
syntax. This syntax means: query the theme for the value of this
semantic attribute.
Medium 上的这个 post 对样式和主题进行了相当详细的解释。
我正在处理一个关于支持库和工具栏的示例,这是 Android 文档
上的布局代码<android.support.v7.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
这是我第一次看到这些 ?attr
,我不知道它们是什么意思,也不知道这些值存储在哪里。这些是自定义的还是在 Android 框架上预定义的?
?attr/
对属性的引用。属性是应用程序主题中指定的值。您示例中的属性都是支持库提供的主题中指定的所有值。 Android 也有自己的属性,可以与 ?android:attr/
一起使用。
最终要使用的实际值取决于用于扩充所述布局的主题。这个主题可以在应用范围主题的 <application/>
块中的清单中指定,或者在特定 activity 的 <activity/>
块中指定。您还可以在运行时使用不同的上下文覆盖此主题(参见 ContextThemeWrapper and LayoutInflater)
在布局中使用主题属性而不是硬编码值被认为是一种很好的做法,因为它可以轻松自定义。例如,当您创建自定义视图时,您可以使用 ?attr/colorAccent
这样视图的用户不必提供颜色,它将使用应用程序主题中使用的 colorAccent
反而。
这在今天变得更加重要,因为在 Android Q 中引入了深色主题,您的布局应该指定一个属性,以便在使用浅色主题和深色主题时最终值不同。
A style attribute resource allows you to reference the value of an attribute in the currently-applied theme.
Rather than setting a static color (
#ffffff
or a@color
resource) we can delegate to the theme by using the?attr/themeAttributeName
syntax. This syntax means: query the theme for the value of this semantic attribute.
Medium 上的这个 post 对样式和主题进行了相当详细的解释。