2011-01-22 106 views
2

在Android资源xml中引用主题的属性值时使用问号(?)而不是(@)。如下面的ListViewCustomStyle:Android访问属性参考

<ListView 
    android:id="@+id/MainScreenListView" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    style="?ListViewCustomStyle"/> 

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

com.myapp.R.attr.ListViewCustomStyle 

然后代码崩溃。有没有特别的方法可以访问它,因为它是对一个项目的引用而不是实际的项目?

回答

5

它可能只是因为你在那里写了ListRowCustomStyle和ListViewCustomStyle在你的xml中而崩溃。

我这样做的方式是例如在标签style =“@ 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> 

您可以通过使用id R.style.my_button

+1

Woops ListRowCustomStyle是一个错字;我已经修复 – 2011-01-22 20:09:31

2

相信在XML访问代码的风格,你想写

风格= “@风格/ ListViewCustomStyle”

无论如何,如何在代码中使用它?

我最后一次检查,这是不可能的:(

我一招做到了:

  1. 创建布局文件,如下例:

    <Button 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    style="@style/MyCustomStyle"/> 
    
  2. 当您想要在代码中添加具有自定义样式的对象时,您必须使用刚刚创建的此布局夸大它:

LayoutInflater inflater = LayoutInflater.from(this); // this = activity or context 
Button button = (Button) inflater.inflate(R.layout.myButtonWithMyStyle, null); //use the same layout file as above 
button.setText("It works!"); 
myView.addView(button); 

这比在代码中创建一个按钮相当慢。如果您使用此方法同时创建Views的Hundread,则可能会出现问题。少于我认为你可以处理它。

+0

好吧,现在它显示了一切(有一些bug隐藏了一些代码) – 2011-01-31 11:58:55