目前我开始致力于支持一个项目,在那里我发现了一个非常有趣的技巧。它提供了一个机会,不要在xml中为CustomView编写完整的类名,它看起来很脏,我想。CustomView安全吗?
下面是此招的实现步骤:
1)在我们的项目中创建我们自己的android.view
包。
2)创建CustomTextView extends TextView
并将其放入android.view
包中。
3)使用它的XML像任何其他Android view
<CustomTextView
android:angle="90"
android:endColor="#efa600"
android:paddingLeft="0dp"
android:startColor="#ffe396"
android:text=""
android:textSize="24dp"
android:textStyle="bold" />
4)使用标准Android属性,而不是定制:
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();
}
请问这样的方式是安全的或者它会导致任何问题?
为什么你想让自己复杂化并使用一些未公开的行为只是为了不将自定义视图的包名键入? – Luksprog
这不是我的代码,我只是支持它,我想知道任何可能的问题。 – Evos