DIRTY DAVE
DIRTY DAVE

Reputation: 2731

onTouchEvent - setter methods not working, but a constructor works. Extremely confused

Here is the full code of the finger paint app:

DrawingView: https://pastebin.com/4t8SUTDJ

MainActivity: https://pastebin.com/rU4nQwUS

MainActivity XML: https://pastebin.com/GLJjRty2

Stroke: https://pastebin.com/ihs03rEW

@Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                touch_up();
                invalidate();
                break;
        }
        return true;
    }

In my touch_up() method I am creating a new stroke object to add into an array, but for some reason setters for the class DO NOT WORK and I have no idea why it's not.

This DOES NOT work:

public DrawingView(Context context) {
        super(context);
        mUserStroke = new Stroke();
}

private void touch_up() {
        mUserPath.lineTo(mUserX, mUserY);
        mUserStroke.setPath(mUserPath);
        mUserStroke.setPaint(mUserPaint);
        mUserList.add(mUserStroke);
        mUserPath = new Path();
}

However changing it to a constructor like so...:

private void touch_up() {
        mUserPath.lineTo(mUserX, mUserY);
        Stroke stroke = new Stroke(mUserPath, mUserPaint);
        mUserList.add(stroke);
        mUserPath = new Path();
}

works perfectly fine. I've been debugging for the entire day on this matter, but now I am beyond confused to why this is an issue.

Edit1:_______________________________________________________

This is the DrawingView using constructor: https://pastebin.com/pZ26v3cg (it works),

but if you use setter methods instead:

https://pastebin.com/4t8SUTDJ

it DOES NOT work.

Here is the video of it: https://youtu.be/02VPZh73e8A

Upvotes: 0

Views: 52

Answers (1)

Haris
Haris

Reputation: 4230

If you are using the same object in the list it will point to the same reference. Changing an object will affect all items in the list.

In your case, all paths inside mUserList will have the same mNativePath.

enter image description here

If you want to keep references to all Paths, then you should initiate a new Stroke object when adding to the mUserList.

enter image description here

Here is a simplified example to understand better why is this happening:

TestObject item = new TestObject();
List items = new ArrayList();
items.add(item);

item.value = "Update 1";
items.add(item);

item.value = "Update 2";
items.add(item);

private class TestObject {
    String value = "Default";
}

Results: enter image description here

Upvotes: 1

Related Questions