2017-04-04 56 views
0

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

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

我觉得你正在使用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显示指定的字符数组的指定切片。

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

+0

感谢这个快速的答案。我会尝试这样。但我也尝试... textView.setText(x1);它也不起作用... – rcode

+0

'text.setText(X1)'将设置为使用**字符串资源标识符。**显示的文本所以你希望它不会工作。 –

+0

我尝试textView.setText(x1 +“”+ y1)。这是唯一的错误 - 现在它工作正常。非常感谢你! – rcode