获取ActionEvent的坐标

时间:2017-04-04 05:16:28

标签: java android motionevent

我有点问题。 在下面的示例中,第一个TextView必须显示MotionEvent的类型 - 它工作正常。第二个TextView必须显示MotionEvent的坐标 - 但它不起作用。我不知道为什么,但也许只是一个小错误? 有没有人有想法? 谢谢你的帮助! 这是代码:

package de.androidnewcomer.motionevent;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import static android.R.attr.x;
import static android.R.attr.y;

public class MainActivity extends AppCompatActivity implements View.OnTouchListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    FrameLayout Spielbereich=(FrameLayout)findViewById(R.id.Spielbereich);
    Spielbereich.setOnTouchListener(this);
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    TextView textView1=(TextView)findViewById(R.id.textView1);
    TextView textView2=(TextView)findViewById(R.id.textView2);
    TextView textView3=(TextView)findViewById(R.id.textView3);
    TextView textView4=(TextView)findViewById(R.id.textView4);
    int x1,x2,y1,y2;
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            x1 = (int)event.getX();
            y1 = (int)event.getY();
            textView1.setText("Action Down");
            textView2.setText(x1,y1);
            return true;
        }
        case MotionEvent.ACTION_UP: {
            x2 = (int)event.getX();
            y2 = (int)event.getY();
            textView3.setText("Action Up");
            textView4.setText(x2,y2);
            return true;
        }
    } return false;
}
}

1 个答案:

答案 0 :(得分:1)

我认为您使用的是setText(...)错误。在docs中,您可以看到TextView具有以下setText方法:

  • final void setText(int resid) 使用字符串资源标识符设置要显示的文本。

  • final void setText(CharSequence text) 设置要显示的文本。

  • void setText(CharSequence text, TextView.BufferType type) 设置要显示的文本和TextView.BufferType。

  • final void setText(int resid, TextView.BufferType type) 使用字符串资源标识符和TextView.BufferType设置要显示的文本。
  • final void setText(char[] text, int start, int len) 设置TextView以显示指定char数组的指定切片。

您正在尝试使用不受支持的setText(int,int)。 您应该执行textView2.setText(x1+" "+y1);

之类的操作
相关问题