Search code examples
javaandroidandroid-framelayoutmotionevent

How to call a function only certain time


I have one EditText and one FrameLayout. I made it in a way where if the user drags within the FrameLayout, the background changes the color (RGB) based on the pixel from (X,Y) coordinate and also updates the EditText with the Hex value converted from the RGB values.

Here is the Pastebin link for my entire code: http://pastebin.com/7P3QSmb4

The issue I am having is with the following code:

if (s.length() == 6) {
    int color = Integer.parseInt(etHexVal.getText().toString(), 16);
    int r = (color >> 16) & 0xFF;
    int g = (color >> 8) & 0xFF;
    int b = (color >> 0) & 0xFF;
    getXY(r, g, b);
    hexToRGB();
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(etHexVal.getWindowToken(), 0);
}

I want to call the function getXY(r, g, b) only when the text of the EditText is changed and I am not dragging within the FrameLayout, because otherwise it would make my app lag. How can I modify my existing code?


Solution

  • Use a variable to lock the call of getXY()

    Declare a new variable

    Boolean callGetXY = true;
    

    Set it to false on ACTION_DOWN and back to true on ACTION_UP

    View.OnTouchListener flTouch = new View.OnTouchListener() {
    
    @Override
    public boolean onTouch(View v, MotionEvent event) {
           // your current content of the method here
           // ...
           if (event.getAction() == MotionEvent.ACTION_DOWN) {
               callGetXY = false;
           }
    
           if (event.getAction() == MotionEvent.ACTION_UP) {
               callGetXY = true;
           }
    
        }
    };
    

    Change line 82 to:

    if (callGetXY) {
        getXY()
    }