Search code examples
androidmotioneventandroid-touch-event

android: how can I detect when user touch left 20% of view area?


In an activity by using

public boolean dispatchTouchEvent(MotionEvent ev)

how can I know an user is touching left Y-axis of 20% edge area?

It should be generic and orientation handled. I don't want to create any hidden view on that.


Solution

    • Get device width
    • Calculate left 20% width size (from 0 to X)
    • Use event.getX()
    • Check that event.getX() is inside device with 20%

    enter image description here

    example :

    public class YourActivity extends Activity {
    
            private LinearLayout background;
            private float xValue, yValue, leftPersentage;
            private int height,width;
    
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_home);
    
                DisplayMetrics displaymetrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                height = displaymetrics.heightPixels;
                width = displaymetrics.widthPixels;
    
                leftPersentage = (width)*20/100;
    
                background = (LinearLayout) findViewById(R.id.background);
                background.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        xValue = event.getX();
                        yValue = event.getY();
                        Log.d("Values Clicked" , xValue +"and" + yValue);
                        if(xValue <= leftPersentage){
                            // perform your task 
                            Log.d("Values Clicked onLeft" , xValue +"and" + yValue);
                        }
    
                        return false;
                    }
                });
            }
        }