android view强制重绘_安卓自定义 view 不能正常重绘

我有一个自定义的 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()

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值