Yes. Quick guide:
1. Create an XML attribute
Create a new XML file inside /res/values/attrs.xml , with the attribute and enter
<?xml version="1.0" encoding="UTF-8"?> <resources> <declare-styleable name="MyCustomElement"> <attr name="distanceExample" format="dimension"/> </declare-styleable> </resources>
Basically, you need to configure one <declare-styleable /> for your view, which contains all your user attributes (there is only one here). I did not find a complete list of possible types, so you need to look at the source that I assume. The types that I know are reference (to another resource), color, boolean, dimensional, float, integer and string. They are pretty clear.
2. Use attributes in the layout
This works the same as you did above, with one exception. Your own attribute needs its own XML namespace.
<com.example.yourpackage.MyCustomElement xmlns:customNS="http://schemas.android.com/apk/res/com.example.yourpackage" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Element..." customNS:distanceExample="12dp" />
Pretty straight forward.
3. Use the obtained values
Modify the custom view constructor to parse the values.
public MyCustomElement(Context context, AttributeSet attrs) { super(context, attrs); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCustomElement, 0, 0); try { distanceExample = ta.getDimension(R.styleable.MyCustomElement_distanceExample, 100.0f); } finally { ta.recycle(); }
distanceExample is a private member variable in this example. TypedArray got a ton of other things to analyze other types of values.
What is it. Use the syntax value in the View to change it, for example. use it in onDraw() to change the look accordingly.
user658042 Sep 30 '11 at 9:57 2011-09-30 09:57
source share