Search code examples
androidanimationviewcursor

Making cursor blink in custom View


In an App I am working on, I have my own custom View. In this View, I draw a cursor using canvas.drawRect() in the View's onDraw() method. This works fine but here's the thing: I want the cursor to blink like most cursors do. If it were an image or some kind of View I could easily do this using AlphaAnimation and setting the repeat count to infinite. However, this won't work because I use canvas.drawRect() to draw the cursor, so my question is: How can I periodically make the cursor appear and disappear in an elegant and simple way?

Edit:

Using blackbelt's input I created the following runnable to do the animation:

// Cursor blink animation
private Runnable cursorAnimation = new Runnable() {
    public void run() {
        // Switch the cursor visibility and set it
        int newAlpha = (mCursorPaint.getAlpha() == 0) ? 255 : 0;
        mCursorPaint.setAlpha(newAlpha);
        // Call onDraw() to draw the cursor with the new Paint
        invalidate();
        // Wait 500 milliseconds before calling self again
        postDelayed(cursorAnimation, 500);
    }
};

In the View's constructor I call post(cursorAnimation) to get it started.


Solution

  • Last parameter of drawRect is a Paint object. You can change the rect alpha through it. You can also use View.postDelayed to decide how to change the alpha value and invalidate the view.