前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android获取点击屏幕的位置坐标

Android获取点击屏幕的位置坐标

作者头像
砸漏
发布2020-11-05 10:46:56
4.5K0
发布2020-11-05 10:46:56
举报
文章被收录于专栏:恩蓝脚本

在Android开发过程中,有时需要获取触摸位置的坐标,以便作进一步处理,比如做炫酷的动画效果,或者响应其他操作。

本文简单介绍Android中触屏操作时,触屏的开始位置、当前位置、结束位置。

布局:

代码语言:javascript
复制
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="com.example.com.TouchTest"  

  <LinearLayout
    android:id="@+id/ll_touch"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"  

    <TextView
      android:id="@+id/touch_show_start"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/hello_world" / 

    <TextView
      android:id="@+id/touch_show"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/hello_world" / 
  </LinearLayout 

</RelativeLayout 

Activity中的操作:

代码语言:javascript
复制
public class TouchTest extends Activity implements OnTouchListener {

  private TextView tvTouchShowStart;
  private TextView tvTouchShow;
  private LinearLayout llTouch;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_touch_test);
    init();
  }

  private void init() {
    tvTouchShowStart = (TextView) findViewById(R.id.touch_show_start);
    tvTouchShow = (TextView) findViewById(R.id.touch_show);
    llTouch = (LinearLayout) findViewById(R.id.ll_touch);
    llTouch.setOnTouchListener(this);
  }

  @Override
  public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
    /**
    * 点击的开始位置
    */
    case MotionEvent.ACTION_DOWN:
      tvTouchShowStart.setText("起始位置:(" + event.getX() + "," + event.getY());
      break;
    /**
    * 触屏实时位置
    */
    case MotionEvent.ACTION_MOVE:
      tvTouchShow.setText("实时位置:(" + event.getX() + "," + event.getY());
      break;
    /**
    * 离开屏幕的位置
    */
    case MotionEvent.ACTION_UP:
      tvTouchShow.setText("结束位置:(" + event.getX() + "," + event.getY());
      break;
    default:
      break;
    }
    /**
    * 注意返回值
    * true:view继续响应Touch操作;
    * false:view不再响应Touch操作,故此处若为false,只能显示起始位置,不能显示实时位置和结束位置
    */
    return true;
  }

}

效果图:

以上就是本文的全部内容,希望对大家的学习有所帮助。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档