I’ve created a class that extends View in order to draw it myself, in a specific position.
I have overriden the onDraw method:
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(pic, x, y, null);
}
When I set a click listener and add the view to a layout, the event fires even when I’m not clicking on the view’s area.
I tried setting the layout parameters to wrap content with no help, tried delete “super.onDraw” didn’t help too.
If I’m doing the same actions with a built in view (like button or image view), it’s not happening.
What’s the problem? Am I doing something wrong?
More code:
public class FlowingPicture extends View {
private float x,y;
private Bitmap pic;
private int screenWidth;
private int screenHeight;
public FlowingPicture(Context context, Bitmap pic, int x, int y, WindowManager screenSize) {
super(context);
screenHeight = screenSize.getDefaultDisplay().getHeight();
screenWidth = screenSize.getDefaultDisplay().getWidth();
this.pic = pic;
this.x = x;
this.y = y;
}
public void move(float x, float y){
this.x += x;
if(this.x > screenWidth)
this.x = -(this.pic.getWidth());
this.y += y;
this.postInvalidate();
}
public float getX(){
return x;
}
public float getY(){
return y;
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(pic, x, y, null);
}
}
The part of the code that creates the view:
for(int i=0; i<arr.size(); i++){
Bitmap b = arr.get(i).getFlowProfilePic();
int x, y;
do{
y = rand.nextInt(screenHeight - b.getHeight() - 30);
x = rand.nextInt(screenWidth);
}
while (!checkPoint(x, b.getWidth(), y, b.getHeight()));
takenPoints.add(new Point(x, y));
FlowingPicture fp = new FlowingPicture(FlowingFeeds.this, b, -(x + b.getWidth()), y, getWindowManager());
fp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(FlowingFeeds.this, "I'm working!", Toast.LENGTH_SHORT).show();
}
});
fp.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
flowingObjectsList.add(fp);
}
parseHandler.sendEmptyMessage(0);
The parseHandler adding the views to the layout:
for(FlowingPicture fp : flowingObjectsList){
layout.addView(fp);
}
flow = new Thread(FlowingFeeds.this);
flow.start();
And the last part:
layout = new FrameLayout(this);
layout.setBackgroundColor(Color.WHITE);
setContentView(layout);
Ok, I didn’t solved it, but I think I know what the problem was.
Because I’m moving the view all across the screen, it gave the view a space in the size fo the screen.
So I just add a touch listener to the layout that the views are on, that take the x and y of the touch and check if this touch is on a some view.
Not the most elegant solution, but I did my best!
Thanks for everyone who tried to help! 🙂