Android访问属性参考

w.d*_*hue 2 android

在Android资源xml中引用主题属性的值,您使用问号(?)而不是(@).如下面的ListViewCustomStyle:

 <ListView 
     android:id="@+id/MainScreenListView" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"
     style="?ListViewCustomStyle"/>
Run Code Online (Sandbox Code Playgroud)

如何在代码中使用ListViewCustomStyle的值?如果我以正常的方式尝试,即

com.myapp.R.attr.ListViewCustomStyle
Run Code Online (Sandbox Code Playgroud)

然后代码崩溃了.是否有一种特殊的方式来访问它,因为它是对项目的引用而不是实际项目?

Jem*_*ems 5

它可能只是崩溃,因为你在那里写了ListRowCustomStyle,并在你的xml中写了ListViewCustomStyle.

我这样做的方法是让标签样式="@ style/my_button"为例(没有android:在它之前).然后,您可以在values/styles.xml文件中定义样式,例如

    <?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="my_button" parent="@android:style/Widget.Button">
        <item name="android:gravity">center_vertical|center_horizontal</item>
        <item name="android:textColor">#FFFFFFFF</item>
    ...
       </style>
</resources>
Run Code Online (Sandbox Code Playgroud)

您可以使用id R.style.my_button访问代码中的样式