Search code examples
javaandroidtouch-event

how to Get coordinates from Custom view android


I have some custom view with onTouchEvent where I'm setting mX and mY .

mx=event.getX();
my=event.getY();

this is for getting the drawing path of touch event - working great, and I can see the coordinates in my text view which is defined in the main activity.

I want to use this 2 attributes in my Main activity layout for setting the background color for example

if (mx > 1000 && my > 100 ){
set color 
}

but it seems that mx and my are not getting any values what i tried is

custom_view paintview = (custom_view) findViewById(R.id.custum_view_id)
float mx =paintview.getmx();
float my =paintview.getmy();

maybe i didn't defined the getmx correctly in custom view ?

public float getmx(){
return mx;
}

i'm new in Java and android so be easy with me :)

adding MainActiviy.

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Drawing - custom view
        drawView = (Drawing) findViewById(R.id.drawing);

        findCoordinates();

        TextView Coordinates = (TextView) findViewById(R.id.CNcoordinates);

        //Coordinates - message with coordinates
        paintView.setTextView(Coordinates);

    }

    private Drawing drawView;


    public void findCoordinates() {
        Drawing paintView = (Drawing) findViewById(R.id.drawing);
        float xX = drawView.getmX();
        float yY = drawView.getmY();
        int nColor = Color.BLUE;
        View buttonmove1 = findViewById(R.id.layoutMove);
        if (Math.abs(xX) > 1000 && Math.abs(yY) > 1000) {
            buttonmove1.setBackgroundColor(nColor);
        }
    }

the coordinates come from:

protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
        canvas.drawPath(drawPath, drawPaint);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {

         mX = event.getX();
         mY = event.getY();

        View buttonmove = findViewById(R.id.drawing);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                drawPath.moveTo(mX, mY);

                if(myCoordinates!=null){
                    myCoordinates.setText(":" + mX + " , " + ":" + mY);
                }
                break;




public void setTextView(TextView tv){
        myCoordinates = tv;
    }

Solution

  • Use interface or callback after finishing your touchEvent. you have to re-call your

    findCoordinates()

    so it will update your UI respect to new values.