I want to make three images randomly appear on screen at certain position in android. And I want to make those images clickable. If you click on a single image which is appeare
You can draw an image on a Canvas using following code.
Rect dst = new Rect(x, y, x + imageWidth,y + imageHeight);
//enter paint as the last arg to use bitmap filtering
canvas.drawBitmap(myBitmap, null, dst, bitmapFilterSettings);
myBitmap is a Bitmap, bitmapFilterSettings is a Paint. Place this code in your onDraw()
method.
In order to place the image randomly, you have to randomize the x
and y
you pass to the dst Rect
. In order to select a random image, you can put you Bitmaps in a List
or an array and use the nextInt(listSize)
method of Random. In order to make the image appear and disappear randomly, use the nextBoolean()
method of Random
and only draw the image if it returns true
. Do not do this too often (once every X frames), or your image will flicker.
EDIT : To do this you can declare a counter in the Activity
and the number of frames between the decisions. You will also need a boolean
field to switch drawing on and off. In your onDraw()
it could look like this:
counter++;
if(counter%framesBetweenDecision == 0){
drawImageFlag = random.nextBoolean();
}
if(drawImageFlag){
//drawImage
}
To make the times between the decisions less predictable you could also randomize the timeBetweenDecision
.
/EDIT
You can handle the touch event in your listener, calling the random image selection on each click. If you want to make only the image part clickable, check the location of your MotionEvent (you can use the getX() and getY() methods) to lie inside the same Rect you are using to draw you image using it's contains(x, y)
method.
This is not the only way to achieve this, but a quite straightforward one.