Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 views
in Technique[技术] by (71.8m points)

What does ?attr/ mean on 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"/>

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?

Reference: Android Toolbar Documentation

question from:https://stackoverflow.com/questions/38165168/what-does-attr-mean-on-android

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

?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/.

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)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...