在代码编写过程中,尽量避免使用自定义属性来定义功能,而是应该通过编写自己的代码来实现所需的功能。若必须使用自定义属性,可以通过下面的示例中的方法来解决依赖问题:
public class CustomView extends View {
private int customAttribute = 0;
public CustomView(Context context) {
super(context);
init(context, null);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
customAttribute = a.getInt(R.styleable.CustomView_customAttribute, 0);
a.recycle();
}
}
在上面的代码示例中,CustomView 中使用了自定义属性 customAttribute ,但是通过使用 TypedArray 对其进行获取,来避免了对 R 文件依赖的问题。注意要在 attrs 中声明自定义属性的名称和类型,如下所示: