问题:渠道方在自定义控件的属性,在xml中配置了自定义属性值,动态循环通过R文件获取映射,导致有的发行方没有处理R文件的重新编译,运行时,闪退找不到对应的资源id。
解决方案:通过TypeArray类代码去设置对应的属性,这样就不用反编译出包时,再次去重新编译R文件处理了。
案例demo如下:
1、自定义xml属性
<resources>
<declare-styleable name="myView">
<attr name="textColor" format="color"/>
<attr name="textSize" format="dimension"/>
</declare-styleable>
</resources>
2、声明一个自定义类
public class MyTextView extends View {
private Paint myPaint;
private static final String myString = "Hello CustomView!";
public MyTextView(Context context){
super(context);
}
public MyTextView(Context context, AttributeSet attr) {
super(context, attr);
myPaint = new Paint();
//添加自定义属性数组
int arr[]=new int[]{ResourceUtil.getStyleableId(context,"myView_textSize"),ResourceUtil.getStyleableId(context,"myView_textColor")};
TypedArray a = context.obtainStyledAttributes(attr, arr);
//设置自定义属性值
float textSize = a.getDimension(ResourceUtil.getStyleableId(context,"myView_textSize"), 10);
int textColor = a.getColor(ResourceUtil.getStyleableId(context,"myView_textColor"), 0xFFFEEFFF);
myPaint.setTextSize(textSize);
myPaint.setColor(textColor);
a.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
//myPaint = new Paint();
myPaint.setColor(Color.RED);
myPaint.setStyle(Paint.Style.FILL);
canvas.drawRect(new Rect(10,10,100,100), myPaint);
myPaint.setColor(Color.WHITE);
canvas.drawText(myString, 10, 100, myPaint);
}
}
919

被折叠的 条评论
为什么被折叠?



