Question mark (?) in XML attributes for Android

醉酒当歌 提交于 2019-11-26 03:49:54

问题


Can anyone explain the question mark means in Android XML attributes?

<TextView    
    style=\"?android:attr/windowTitleStyle\"
    More attributes
/>

回答1:


The question mark means it's a reference to a resource value in the currently applied theme. See the linuxtopia Android Dev Guide or the android.com Dev Guide for more about it.

\? escapes the question mark.




回答2:


The ? lets you refer to a style attribute instead of a specific hard-coded resource. See "Referencing style attributes" in the Android Dev Guide for details.

So, how is this actually useful? It makes the most sense when considering multiple themes containing the same custom resource attribute.

Say you have movie-related themes like MyThemeTransformers and MyThemeHobbit, and both have an attribute called movieIcon. And that movieIcon attribute points to a different @drawable resource, say robot.png or hobbit.png, in each theme definition.

You can refer to "?attr/movieIcon" anywhere the theme is in effect (like in a toolbar or dialog or whatever kind of View layout), and it will automatically point to the correct drawable when you switch between themes. You don't need any theme-dependent logic to use the different drawables. You just define the movieIcon attribute for each theme and the Android framework takes care of the rest.



来源:https://stackoverflow.com/questions/2733907/question-mark-in-xml-attributes-for-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!