Android touch events on surface view

Android touch events on surface view

0 404

Android Coding

With coding example for Android development
Here Override onTouchEvent() in SurfaceView to deal with user touch event.

Handle onTouchEvent in SurfaceView

package com.TestSurefaceView

import java.util.Random
import android.application.Activity
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Fresh paint
import android.os.Bundle
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView

public class TestSurefaceView stretches Activity Known as once the activity is first produced. */
@Override
public void onCreate(Bundle savedInstanceState)

@Override
protected void onResume() produced method stub
super.onResume()
mySurfaceView.onResumeMySurfaceView()

@Override
protected void onPause() produced method stub
super.onPause()
mySurfaceView.onPauseMySurfaceView()

class MySurfaceView stretches SurfaceView implements RunnableFresh paint fresh paint = new Fresh paint(Fresh paint.ANTI_ALIAS_FLAG)
Random random

volatile boolean touched = false
volatile float touched_x, touched_y

public MySurfaceView(Context context) produced constructor stub
surfaceHolder = getHolder()
random = new Random()

public void onResumeMySurfaceView()

public void onPauseMySurfaceView() catch (InterruptedException e) produced catch block
e.printStackTrace()

@Override
public void run() produced method stub
while(running)fresh paint.setStyle(Fresh paint.Style.STROKE)
fresh paint.setStrokeWidth(3)

int w = canvas.getWidth()
int h = canvas.getHeight()
int x = random.nextInt(w-1)
int y = random.nextInt(h-1)
int r = random.nextInt(255)
int g = random.nextInt(255)
int b = random.nextInt(255)
fresh paint.setColor(0xff000000 + (r << 16) + (g << 8) + b)
canvas.drawPoint(x, y, fresh paint)

if(touched)fresh paint.setStrokeWidth(50)
fresh paint.setColor(Color.BLACK)
canvas.drawPoint(touched_x, touched_y, fresh paint)

surfaceHolder.unlockCanvasAndPost(canvas)

@Override
public boolean onTouchEvent(MotionEvent event) produced method stub

touched_x = event.getX()
touched_y = event.getY()

int action = event.getAction()
switch(action)situation MotionEvent.ACTION_Lower:
touched = true
break
situation MotionEvent.ACTION_MOVE:
touched = true
break
situation MotionEvent.ACTION_UP:
touched = false
break
situation MotionEvent.ACTION_CANCEL:
touched = false
break
situation MotionEvent.ACTION_Outdoors:
touched = false
break
default:

return true //processed

NO COMMENTS

Leave a Reply