简体   繁体   中英

setting a drawText object visible and invisible android

I want to set a drawText object visible and invisible with just a click. It'll start as invisible but when the user tap anywhere on the screen, the object will appear and vice versa, after tapping again the object will be invisible again.

Here's my code

public void onDraw(Canvas canvas) {

        if (GetterSetter.isVisible) {

            renderText(canvas);

        }
}

private void renderText(Canvas canvas) {
        Paint textPaint = new Paint();
        textPaint.setTextSize(18);
        textPaint.setAntiAlias(true);
        textPaint.setARGB(0xff, 0x00, 0x00, 0x00);
        canvas.drawText(GetterSetter.currLoc, 16, 50, textPaint);

    }

here's my onTouchEvent

@Override
    public boolean onTouchEvent(MotionEvent e) {

        x = e.getX();
        y = e.getY();

        switch (e.getAction()) {
        case MotionEvent.ACTION_MOVE:
            if (GetterSetter.counter < 1) {
                GetterSetter.counter++;
                GetterSetter.isVisible = true;
            } else {
                GetterSetter.counter = 0;
                GetterSetter.isVisible = false;
            }
            break;
        }

        return true;
    }

and here are my constants: GetterSetter.java

public static String currLoc = "Hello World";

    public static boolean isVisible = false;

    public static int counter = 0;

My problem is, its not working. I don't know how should I make it work aside from what I've done so far.

Just use the fact that if it is not visible, set it to visible and vise versa. And don't use static declaration for isVisible since you want to change it.

  case MotionEvent.ACTION_MOVE:
        if (!GetterSetter.isVisible) {
            GetterSetter.isVisible = true;
        } else {
            GetterSetter.isVisible = false;
        }
        break;

make the View to draw it contents when you change the value of isVisible value by calling invalidate() ... and as you want to listen for tap event, use ACTION_UP event instead of ACTION_MOVE ...

public boolean onTouchEvent(MotionEvent e) {
    x = e.getX();
    y = e.getY();
    switch (e.getAction()) {
    case MotionEvent.ACTION_UP:
        GetterSetter.isVisible = !GetterSetter.isVisible;
        invalidate();
        break;
    }
    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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