Android access attribute reference
In the Android resources xml to reference the value of an attribute for a theme you use the question-mark (?) instead of at (@). Such as ListViewCustomStyle below:
<ListView
android:id="@+id/MainScreenListView"
android:layout_width="fill_parent" 开发者_如何学C
android:layout_height="wrap_content"
style="?ListViewCustomStyle"/>
How can I use the value of the ListViewCustomStyle in code? If I try it the normal way i.e.
com.myapp.R.attr.ListViewCustomStyle
Then the code crashes. Is there a special way to access this since it is a reference to an item and not an actual item?
It might just be crashing because you wrote ListRowCustomStyle there, and ListViewCustomStyle in your xml.
The way I do this is to have the tag style="@style/my_button" for example (with no android: preceding it). Then you can define your style in the values/styles.xml file, e.g.
<?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>
You can access the style in code by using the id R.style.my_button
I believe in the xml you wanted to write
style="@style/ListViewCustomStyle"
Anyway, how to use it in code?
Last time I check, it was impossible :(
I did it with a trick:
create a layout file as the example that follows:
<Button android:layout_width="fill_parent" android:layout_height="wrap_content" style="@style/MyCustomStyle"/>
when you want to add an object with your custom style in code, you have to inflate it, using this layout you just created:
:
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);
This is considerably slower than creating a Button in code. It may be a problem if you create hundreads of Views at the same time using this method. Less than that I think you can handle it.
精彩评论