简体   繁体   English

无效仅在自定义视图中有效

[英]invalidate only works in custom view

so i created a view called "drawable view" 所以我创建了一个称为“可绘制视图”的视图

 class DrawableView extends View{
        Context mContext;

        int touches=0,k,Xoffs,clicks=0;


  double x_1 = 0,x_2=0;

        private float mLastTouchX, mLastTouchY;

        public DrawableView(Context context) {
        super(context);
        mContext = context;
        }

....
    @Override
    protected void onDraw(Canvas canvas){

        Paint myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

canvas.drawColor(Color.BLUE);
myPaint.setColor(Color.WHITE);

canvas.drawCircle(200, 100, 20, myPaint);


    }

..... more code....

}

and it can only be invalidated within the ondraw command! 并且只能在ondraw命令中使它无效! ie: calling "invalidate();" 即:调用“ invalidate();” at the end of the ondraw command causes it to loop. 在ondraw命令的末尾使它循环。

I have tried many times to call g_draw.invalidate(); 我已经尝试了很多次来调用g_draw.invalidate(); or g_draw.postInvalidate(); 或g_draw.postInvalidate();或 (g_draw is the name of the created Drawable View)from other classes and even the main activity class and it doesnt work. (g_draw是创建的Drawable View的名称)来自其他类,甚至是主活动类,它不起作用。 why and how can i fix it? 为什么以及如何解决?

thanks 谢谢

If you want continious onDraw invoking try doing it in another thread. 如果要连续调用onDraw,请尝试在另一个线程中进行。 Create a thread, and from its run method try doing postInvalidate. 创建一个线程,然后从其运行方法尝试执行postInvalidate。

It always worked for me. 它总是为我工作。

Another thing is that when you draw a circle once, next time wont make any difference - it will look the same. 另一件事是,当您绘制一次圆时,下一次不会有任何变化-它看起来将相同。

You may want to call invalidate() somewhere in your DrawableView class. 您可能想在DrawableView类中的某个地方调用invalidate()。 For example, if you want your view to redraw itself after any touch event, you would do something like this: 例如,如果您希望视图在任何触摸事件后重绘,则可以执行以下操作:

public boolean onTouchEvent( MotionEvent event) {

    if(event.getAction() == MotionEvent.ACTION_UP){
        invalidate();
    }
}

This is how I draw the movable pieces in my puzzle game. 这就是我在益智游戏中绘制活动棋子的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM