在Android资源xml中引用主题属性的值时,使用问号(?)而不是(@)。如下面的ListViewCustomStyle:
<ListView
android:id="@+id/MainScreenListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?ListViewCustomStyle"/>
如何在代码中使用ListViewCustomStyle的值?如果我以正常的方式尝试,即
com.myapp.R.attr.ListViewCustomStyle
然后代码崩溃了。是否有一种特殊的方式来访问它,因为它是对项目的引用而不是实际的项目?
答案 0 :(得分: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>
您可以使用ID R.style.my_button
访问代码中的样式答案 1 :(得分:2)
我相信你想写的xml
<强>风格= “@风格/ ListViewCustomStyle”强>
无论如何,如何在代码中使用它?
上次检查时,这是不可能的:(
我用一招来做到了:
创建一个布局文件,如下例所示:
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="@style/MyCustomStyle"/>
如果要在代码中添加自定义样式的对象,则必须使用刚刚创建的布局对其进行充气:
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);
这比在代码中创建Button要慢得多。如果使用此方法同时创建视图的hundreads,则可能会出现问题。不到我认为你可以处理它。