Featured post
android - How to pass custom component parameters in java and xml -
when creating custom component in android asked how create , pass through attrs property constructor.
it suggested when creating component in java use default constructor, i.e.
new mycomponent(context);
rather attempting create attrs object pass through overloaded constructor seen in xml based custom components. i've tried create attrs object , doesn't seem either easy or @ possible (without exceedingly complicated process), , accounts isn't required.
my question then: efficient way of construction custom component in java passes or sets properties have otherwise been set attrs object when inflating component using xml?
(full disclosure: question offshoot of creating custom view)
you can create constructors beyond 3 standard ones inherited view
add attributes want...
mycomponent(context context, string foo) { super(context); // foo }
...but don't recommend it. it's better follow same convention other components. make component flexible possible , prevent developers using component tearing hair out because yours inconsistent else:
1. provide getters , setters each of attributes:
public void setfoo(string new_foo) { ... } public string getfoo() { ... }
2. define attributes in res/values/attrs.xml
can used in xml.
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="mycomponent"> <attr name="foo" format="string" /> </declare-styleable> </resources>
3. provide 3 standard constructors view
.
if need pick out of attributes in 1 of constructors takes attributeset
, can do...
typedarray arr = context.obtainstyledattributes(attrs, r.styleable.mycomponent); charsequence foo_cs = arr.getstring(r.styleable.mycomponent_foo); if (foo_cs != null) { // foo_cs.tostring() } arr.recycle(); // when done.
with done, can instantiate mycompnent
programmatically...
mycomponent c = new mycomponent(context); c.setfoo("bar");
...or via xml:
<!-- res/layout/myactivity.xml --> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:blrfl="http://schemas.android.com/apk/res-auto" ...etc... > <com.blrfl.mycomponent android:id="@+id/customid" android:layout_weight="1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" blrfl:foo="bar" blrfl:quux="bletch" /> </linearlayout>
- Get link
- X
- Other Apps
Comments
Post a Comment