attr/在Android上是什么意思? [英] What does ?attr/ mean on Android?

查看:209
本文介绍了attr/在Android上是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究有关支持库和工具栏的示例,这是Android文档中布局的代码

I am working on an example about Support Library and Toolbar, this is the code of the layout on the Android documentation

<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框架上预定义的?

It is the first time I see these ?attr and I have no clue about what they mean or where are these values stored. Are these custom or are they predefined on the Android framework?

参考: Android工具栏文档

推荐答案

?attr/对属性的引用.属性是在应用程序主题中指定的值.您的示例中的属性是支持库提供的主题中指定的所有值. Android也有自己的属性,可以与?android:attr/一起使用.

?attr/ references to attributes. Attributes are values specified in an app's theme. The attributes in your example are all values specified in the themes provided by the support library. Android also has its very own attributes which can be used with ?android:attr/.

最后将使用的实际值取决于用于使所述布局膨胀的主题.可以在应用范围内的主题的<application/>块的清单中指定该主题,对于特定活动,可以在<activity/>块的清单中指定此主题.您还可以在运行时通过使用其他上下文覆盖此主题(请参见 ContextThemeWrapper LayoutInflater )

The actual value that is going to be used in the end depends on the theme used to inflate the said layout. This theme can be specified in the manifest in the <application/> block for an app wide theme or in the <activity/> block for a specific activity. You can also override this theme during runtime by using a different context (see ContextThemeWrapper and LayoutInflater)

在布局中使用主题属性而不是硬编码值被认为是一种好习惯,因为它可以轻松自定义.例如,当您创建自定义视图时,可以使用?attr/colorAccent,以便视图的用户不必提供颜色,而是将使用应用程序主题中使用的colorAccent.

It is considered good practice to use theme attributes instead of hardcoded values in your layouts, as it allows for easy customization. For example, when you create custom views, you can use ?attr/colorAccent so that the user of the view doesn't have to provide a color, and it is going to use the colorAccent used in the app themes instead.

今天,这一点变得更加重要,因为Android Q中引入了深色主题,因此您的布局应指定一个属性,以使使用浅色主题与深色主题时的最终值有所不同.

This becomes even more relevant today, as with the introduction of Dark Themes in Android Q, your layouts should specify an attribute so that the end value is different when using a light theme vs a dark theme.

这篇关于attr/在Android上是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆