http://droid-blog.net/2012/04/24/how-to-add-attributes-to-your-custom-view/
How to add attributes to your custom View
Jack just asked the following questions on the tutorial for animated GIFs I once wrote:
“I want to be able to place the GifMovieView in an existing layout (like any regular control).
Please give me a step-by-step of how to bind xml layout attributes to this custom view.”
A good question. Here’s the answer.
To place your own View in an layout XML file, just use it like a normal view, only that you have to append the whole package name up front. Something like:
< eu.andlabs.tutorial.animatedgifs.views.GifMovieView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/my_id"
/>
In this XML, you can already use the standard Android attributes.
If you want to define your own, custom attributes, go to the res/values
-folder and create a file called attrs.xml.
You can define your custom attributes here. In the end, it should look like this:
< ?xml version="1.0" encoding="utf-8"?>
< resources>
< declare-styleable name = "eu.andlabs.tutorial.animatedgifs.view.GifMovieView">
< attr name="url" format="string" />
< attr name="fetchAutomatically" format="boolean" />
< /declare-styleable>
< /resources>
You can now address these attributes in your XML layout. To do so, add something like
xmlns:gif="http://schemas.android.com/apk/res-auto"
To your root layout element. Please notice that this only works with ADT 17 and older. Now you can access your attributes in your layout like this:
< eu.andlabs.tutorial.animatedgifs.views.GifMovieView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/my_id"
gif:url="http://mygif.com/mygif.gif"
gif:fetchAutomatically="true"
/>
Since the XML is done, it’s time to address the Java part, which means the custom View. You should at least overwrite the constructor that is receiving a Context and an Attributes-object. Like so:
public GifMovieView(final Context context, final AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
You can now access your custom attributes in using the AttributeSet:
private void init(final AttributeSet attrs) {
if (attrs != null) {
String packageName = "http://schemas.android.com/apk/res/res-auto";
mUrl = attrs.getAttributeValue(packageName, "url");
mFetchAutomatically = attrs.getAttributeBooleanValue(packageName, "fetchAutomatically", false);
}
}
Do whatever is needed with it. That’s already it.
I hope you enjoyed this post. Please feel free to ask anything you want in the comments.
And remember: Sharing is caring!
- See more at: http://droid-blog.net/2012/04/24/how-to-add-attributes-to-your-custom-view/#sthash.XrTrmwOM.dpuf