我是 Android 新手,我已经按照 hello world 教程进行操作,并且对正在发生的事情有一个基本的了解。我对我的 T-Mobile Pulse 的触摸屏特别感兴趣,所以为了让我开始,我希望能够在屏幕上写下一个 tocuh 事件的坐标,所以假设用户触摸了坐标 5 ,2 - 屏幕上的 TextView 会显示它。
目前我有一个简单的程序,它只加载一个 xml 文件,其中包含我打算在其中写入坐标的 TextView 。
提前感谢您,我在 Google 上寻求帮助并搜索了 stackoverflow,但我发现的所有内容要么超出了我的想象,要么不适合此操作。干杯。
最佳答案
你可能会大致这样把它放在你的 onCreate 方法中(这次测试过):
Activity onCreate 代码
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textView = (TextView)findViewById(R.id.textView);
// this is the view on which you will listen for touch events
final View touchView = findViewById(R.id.touchView);
touchView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
textView.setText("Touch coordinates : " +
String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
return true;
}
});
}
布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/touchView"
android:background="#f00"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, TestActivity"
/>
</LinearLayout>
编辑:我尝试了我的代码,确实有一些错误。无论如何,我在这里给你的布局可以在我的模拟器上运行。您能否提供更多代码/上下文,以便我查看问题所在?
关于android - 获取 Android 上触摸事件的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2939332/