Currently i start working on support of one project, and there i found one very intresting trick. It give an oportunity do not write full class name for CustomView in xml and it look’s pretty dirty i think.
Here are steps for this trick implementation:
1) Create our own android.view package in our project.
2) Create CustomTextView extends TextView and put it in android.view package.
3) Use it in XML like any other Android view
<CustomTextView
android:angle="90"
android:endColor="#efa600"
android:paddingLeft="0dp"
android:startColor="#ffe396"
android:text=""
android:textSize="24dp"
android:textStyle="bold" />
4) Use standard Android attributes instead of custom :
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
int[] ids = new int[attrs.getAttributeCount()];
for (int i = 0; i < attrs.getAttributeCount(); i++) {
ids[i] = attrs.getAttributeNameResource(i);
}
TypedArray a = context.obtainStyledAttributes(attrs, ids, defStyle, 0);
for (int i = 0; i < attrs.getAttributeCount(); i++) {
String attrName = attrs.getAttributeName(i);
if (attrName == null)
continue;
if (attrName.equals("startColor")) {
mStartColor = a.getColor(i, -1);
} else if (attrName.equals("endColor")) {
mEndColor = a.getColor(i, -1);
} else if (attrName.equals("angle")) {
mAngle = a.getFloat(i, 0);
}
}
a.recycle();
}
Does such way is safe or maybe it can cause any problems?
Although it can be done, I would recommend using your own styles.
I’m not sure what would happen if these were removed the future if they would be ignored by the Inflater as they are not valid stylables.
Least to say it would be put you at ease to just use custom styles.
Not to mention MUCH cleaner code.