android-当我触摸按钮时,如何获取触摸相对于整个视图的xy位置?

android-当我触摸按钮时,如何获取触摸相对于整个视图的xy位置?,第1张

概述我想要相对于整个屏幕的触摸信息,但是我只是相对于按钮获得触摸信息.ButtonTouchListener=newOnTouchListener(){publicbooleanonTouch(Viewv,MotionEventevent){if(event.getAction()==MotionEvent.ACTION_DOWN){switch(v.getId()){

我想要相对于整个屏幕的触摸信息,但是我只是相对于按钮获得触摸信息.@H_403_1@

@H_403_1@

buttontouchListener = new OntouchListener(){    public boolean ontouch(VIEw v, MotionEvent event) {        if (event.getAction() == MotionEvent.ACTION_DOWN) {             switch(v.getID()){                case R.ID.somebutton                          //do things                    //....etc            }           int action = event.getAction();       switch(action){       case MotionEvent.ACTION_UP:         act += event.toString();         System.out.println("release: " + act);}};

我从事件中获得的x和y与按钮有关(0,0是按钮的角,而不是屏幕的角).仅当按下按钮时,如何才能获得相对于整个屏幕的x和y位置?@H_403_1@

解决方法:@H_403_1@

要获得相对于视图的触摸位置,请将触摸事件的(x,y)添加到按钮的(x,y);要获取按钮相对于其父控件(您的视图)的位置,请使用getleft()和gettop()方法.@H_403_1@

VIEw的documentation在“位置”下具有以下内容:@H_403_1@

@H_403_1@

It is possible to retrIEve the location of a vIEw by invoking the
methods getleft() and gettop(). The former returns the left, or X,
coordinate of the rectangle representing the vIEw. The latter returns
the top, or Y, coordinate of the rectangle representing the vIEw.
These methods both return the location of the vIEw relative to its
parent. For instance, when getleft() returns 20, that means the vIEw
is located 20 pixels to the right of the left edge of its direct
parent.
@H_403_1@

您的ontouch方法的示例代码:@H_403_1@

@H_403_1@

float screenX = v.getleft() + event.getX();   // X in Screen Coordinatesfloat screenY = v.gettop() + event.getY();    // Y in Screen Coordinates
总结

以上是内存溢出为你收集整理的android-当我触摸按钮时,如何获取触摸相对于整个视图的x / y位置?全部内容,希望文章能够帮你解决android-当我触摸按钮时,如何获取触摸相对于整个视图的x / y位置?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1087458.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存