Search code examples
javaandroidtouchontouch

Creating view on touch coordinates but it gives wrong x and y


In this project i'm aiming to do, when the user touches the screen, it prompt an actions to do, i have used QuickAction to do the action thing, but when i use onTouch, create a view with its x and y, give me the action view in wrong coordinates.

RelativeLayout mine;
QuickAction quickIntent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mine = (RelativeLayout) LayoutInflater.from(EmptyActivity.this).inflate(R.layout.activity_empty, null, false);
    setContentView(mine);


    quickIntent = new QuickAction(EmptyActivity.this, QuickAction.HORIZONTAL);
    quickIntent.addActionItem(new ActionItem(1, "Star", android.R.drawable.star_on));
    quickIntent.addActionItem(new ActionItem(2, "Star", android.R.drawable.star_on));
    quickIntent.addActionItem(new ActionItem(3, "Star", android.R.drawable.star_on));

}

@Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int)event.getX();
    int y = (int)event.getY();
    if(event.getAction() == MotionEvent.ACTION_DOWN){
        View v = new View(EmptyActivity.this);
        v.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        v.setLayoutParams(new LinearLayout.LayoutParams(5, 5));
        v.setX(x);
        v.setY(y);
        mine.addView(v);
        quickIntent.show(v);

        return true;
    }

    return super.onTouchEvent(event);
}

enter image description here

As in the image, but when i increase the Y, its works fine.

v.setY(y-215);

enter image description here

Thanks.


Solution

  • When you touch on Activity window it giving y value with actionBar height.

    So you have to subtract the actionBar height from y.

    Code for ActiobBar height

    final TypedArray styledAttributes = getBaseContext().getTheme().obtainStyledAttributes(
                new int[] { android.R.attr.actionBarSize });
    int mActionBarSize = (int) styledAttributes.getDimension(0, 0);
                styledAttributes.recycle();
    

    Now your y value will be

    y = y-mActionBarSize;
    

    To be more accurate TitleBar height is also need to subtract.