我有一个自定义的 view,放在一个 fragment 里面,fragment 则是在 ViewPager 里面。我在 view 里面定义了一个 setProgress 方法,设置属性 progress 的值并且重绘这个 view,我在 fragment 的 onCreateView 里面调用这个方法,但是当 app 启动的时候这个 SpeedometerView 和在 xml 布局里面预览的一样,没有发生改变,但是当我在 viewpager 里面切换 fragment 时这个自定义的 view 又能正常重绘并显示了。
我在 debug 时发现 setprogress 方法里的 invalidate 方法被调用并在 ondraw 里重绘了这个 view,但是之后 ondraw 方法又被调用了一次并且最后又显示预览时的默认的图形。
public class SpeedometerView extends View {
private float progress;
private Paint arcPaint;
private int arcBgColor;
private int arcFgColor;
private RectF oval;
private float padding;
public SpeedometerView(Context context) {
this(context,null);
}
public SpeedometerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.SpeedometerView);
arcBgColor= typedArray.getColor(R.styleable.SpeedometerView_arcBgColor,Color.GRAY);
arcFgColor=typedArray.getColor(R.styleable.SpeedometerView_arcFgColor,Color.YELLOW);
padding=typedArray.getDimension(R.styleable.SpeedometerView_padding,5);
typedArray.recycle();
oval=new RectF();
arcPaint =new Paint();
arcPaint.setColor(arcBgColor);
arcPaint.setAntiAlias(true);
arcPaint.setStrokeWidth(10f);
arcPaint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float baseDimen=getWidth()<getHeight()?getWidth():getHeight();
float ovalLeft=getWidth()/2f-baseDimen/2+padding;
float ovalRight=getWidth()/2f+baseDimen/2-padding;
float ovalTop=getHeight()/2f-baseDimen/2+padding;
float ovalBottom=getHeight()/2f+baseDimen/2-padding;
oval.set(ovalLeft,ovalTop,ovalRight,ovalBottom);
canvas.drawArc(oval,135,270,false, arcPaint);
arcPaint.setColor(arcFgColor);
float angle=270*(progress/100);
Log.d("draw","ondraw");
canvas.drawArc(oval,135,angle,false, arcPaint);
}
public float getProgress() {
return progress;
}
public void setProgress(float progress) {
this.progress = progress;
invalidate();
}
}
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_health,container,false);
gasHealthSmv=view.findViewById(R.id.gas_health_smv);
envHealthSmv=view.findViewById(R.id.env_health_smv);
gasHealthSmv.setProgress(20);
return view;
}
1
ijkm1234 OP 好吧,我在重绘之前已经把 paint 颜色给改了
|
2
xlsepiphone 2018-09-18 10:28:30 +08:00 via Android
该贴终结
|