user2062024
user2062024

Reputation: 3661

Android - doing a task while a view is being touched? How?

I am trying to make a simple app which does the following. There is an ImageView and a SurfaceView for mediaPlay.

  1. If this view is not touched, do nothing.
  2. If this view is being touched, leave a log message every 100 ms.

Assumption - we have printLogMsg() already available for 2.

So what I am gonna do is to set a onTouchListener to the imageView. My question is, how can I perform printLogMsg() within this onTouchListener.

private OnTouchListener mTouchListener = new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.d("log", "!!!down");
                break;

            case MotionEvent.ACTION_HOVER_ENTER:
                Log.d("log", "!!!hover enter");
                break;

            case MotionEvent.ACTION_UP:
                Log.d("log", "!!!up");
                break;
        }

        return false;
    }
};

I have something like this but touching the ImageView will print "down" just once. Is there a way to do this? Thanks!

Thanks :)

Upvotes: 0

Views: 49

Answers (1)

Bojan Kseneman
Bojan Kseneman

Reputation: 15668

You can do something like that.

private android.os.Handler handler;
private Runnable someTask;

Initialize them somehwere

private void init(){
    handler = new Handler(Looper.getMainLooper());
    someTask = new Runnable() {
        @Override
        public void run() {
            // Do what you want
            printLogMsg();
            handler.postDelayed(this, 100);
        }
    };
}

And the onTouch method

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_UP:
            handler.removeCallbacks(someTask);
            return true;
        case MotionEvent.ACTION_DOWN:
            handler.postDelayed(someTask, 100);
        default:
            return super.onTouchEvent(event);
    }
}

Upvotes: 1

Related Questions