有人可以解释attr吗?

Fue*_*ers 85 android attributes android-layout android-theme

我正在查看Honeycomb Gallery示例代码(此处),并在尝试在我自己的应用程序中添加操作项时遇到以下代码:

<item android:id="@+id/camera"
    android:title="Camera"
    android:icon="?attr/menuIconCamera"
    android:showAsAction="ifRoom" />
Run Code Online (Sandbox Code Playgroud)

?attr让我陷入了困境.有人可以解释一下这是做什么的吗?这与抽象有什么关系?我似乎无法在Google上找到任何有用的信息.还有一个列表或属性库我们可以用于图标,而不仅仅是menuIconCamera

谢谢

编辑:我做了一些调查,发现attrs.xml看起来像这样:

<resources>
<declare-styleable name="AppTheme">
    <attr name="listDragShadowBackground" format="reference" />
    <attr name="menuIconCamera" format="reference" />
    <attr name="menuIconToggle" format="reference" />
    <attr name="menuIconShare" format="reference" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

不幸的是,这让我更加困惑.这是做什么的?

Mic*_*ael 60

?attr/menuIconCamera值表示将使用来自menuIconCamera当前主题的属性的图标.

必须menuIconCamerathemes.xml文件中的某个位置为该属性分配一个drawable .如果有两个主题具有此属性的不同值,则实际图标将取决于当前使用的主题.

attrs.xml文件用于定义自定义属性.如果没有此定义,编译器会将未知属性视为错误.


Pet*_*ego 49

?attr:语法用于访问当前主题的属性.请参阅引用样式属性.

  • 提供的链接非常非常有用.谢谢! (3认同)
  • 非常有帮助,但您仍应发布该链接的主要部分. (3认同)

szi*_*qui 21

我知道这篇文章很老,但我觉得以下解释有助于初学者轻松理解.

所以用外行人的话说,

someAttribute="?attr/attributeName" 意思是 -

someAttribute的值设置为当前主题中attributeName的值

在设计工具栏时会出现一个常见的例子

<style name="AppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/primary_color</item>
       //some more stuff here
</style>
<!-- custom toolbar style -->
<style name="myToolbar" parent="Widget.AppCompat.Toolbar">
      <item name="android:background">?attr/colorPrimary</item>
     //some code here
</style>
Run Code Online (Sandbox Code Playgroud)

这里的值android:background将被设置为@color/primary_color因为在当前主题中?attr/colorPrimary引用@color/primary_color(AppTheme)


小智 15

我的英语不好,抱歉.但我知道这个问题

android:icon="?attr/menuIconCamera" 想用

attrs.xml

<resources>
    <declare-styleable name="AppTheme">
        <attr name="listDragShadowBackground" format="reference" />
        <attr name="menuIconCamera" format="reference" />
        <attr name="menuIconToggle" format="reference" />
        <attr name="menuIconShare" format="reference" />
    </declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)

styles.xml

<style name="AppTheme.Light" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/ActionBar.Light</item>
        <item name="android:windowActionBarOverlay">true</item>
        <item name="listDragShadowBackground">@android:color/background_light</item>
        <item name="menuIconCamera">@drawable/ic_menu_camera_holo_light</item> //this....
        <item name="menuIconToggle">@drawable/ic_menu_toggle_holo_light</item>
        <item name="menuIconShare">@drawable/ic_menu_share_holo_light</item>
    </style>
Run Code Online (Sandbox Code Playgroud)

使用 @drawable/ic_menu_camera_holo_light