Search code examples
androidandroid-animationandroid-transitionsandroid-touch-event

Transition / Animation (onTouchListener)


So here is the code of simple transitioning,from top_left to bottom_right, I dont understand why I have to return false for onTouch() to work properly,

1.If I set return true, one a single touch , it sets counter from 0 to 3 , or simply adds 2 or 3 to the counter and most of the time remains at its current position.

2.If I set return false, the program runs fine and does what is written ,i.e counter++;

public class MainActivity extends AppCompatActivity {
    Button b;
    TextView tv;

    public static int counter_button=0,counter=0;
    RelativeLayout.LayoutParams old_rules;
    RelativeLayout rl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b= (Button) findViewById(R.id.b1);
        tv= (TextView) findViewById(R.id.tv1);
        rl= (RelativeLayout) findViewById(R.id.rl);
        old_rules= (RelativeLayout.LayoutParams) b.getLayoutParams();
        rl.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
               my_changes_touch();
                return false;
            }
        });
    }

    public void my_changes_touch(){

        RelativeLayout.LayoutParams rules= new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
        if(counter%2==0) {
            counter++;
            tv.setText(" "+counter);
            rules.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            rules.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            b.setLayoutParams(rules);
            rules.height=400;
            rules.width=400;
            b.setLayoutParams(rules);
            getContentTransitionManager().beginDelayedTransition(rl);
        } else {
            counter++;
            tv.setText(" "+counter);
            b.setLayoutParams(old_rules);
            getContentTransitionManager().beginDelayedTransition(rl);
        }    
    }
}

Solution

  • The return value determines the event is consumed by the view or not.

    So true means that you are interested in other events also.

    If you return false then the touch event will be passed to the next View further up in the view hierarchy and you will not receive any further calls.

    Please check this answer https://stackoverflow.com/a/3756619/2783541