这段代码出了什么问题。当我从上到下播放屏幕时,我希望写入“Down”文本,而不是另一面。但是在模拟器上没有任何变化。问题是什么?
public class Draw extends View{
int ratioX = 50;
int ratioY = 350;
float dx = 0;
float dy = 0;
int newX;
int newY;
String dir="Hello";
public Draw(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public boolean onTouchEvent(MotionEvent event){
float touchX = 0;
float touchY = 0;
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
touchX = event.getX();
touchY = event.getY();
return true;
case MotionEvent.ACTION_UP:
dx = touchX - event.getX();
dy = touchY - event.getY();
if(Math.abs(dy) > Math.abs(dx)){
if(dy > 0){
dir = "DOWN";
}
else{
dir = "UP";
}
}
else{
if(dx > 0){
dir = "RIGHT";
}
else{
dir = "LEFT";
}
}
}
return true;
}
public void onDraw(Canvas c){
//Rect myRect = new Rect();
//myRect.set(ratioX,c.getHeight()/8,ratioY,c.getWidth()/8);
Paint p = new Paint();
p.setStyle(Paint.Style.FILL);
p.setColor(Color.BLACK);
c.drawPaint(p);
//p.setColor(Color.WHITE);
//c.drawRect(myRect, p);
p.setColor(Color.WHITE);
p.setTextSize(18);
c.drawText(dir, 200, 360, p);
}
}
当我浏览屏幕时没有任何反应!或者我应该使用其他方法?
答案 0 :(得分:0)
当您想要更改其内容时,您需要invalidate()
您的观点。下面的代码片应该会有所帮助;
public boolean onTouchEvent(MotionEvent event) {
// Other parts of method omitted for brevity
case MotionEvent.ACTION_UP:
dx = touchX - event.getX();
dy = touchY - event.getY();
String newDir = dir;
if(Math.abs(dy) > Math.abs(dx)){
if(dy > 0){
newDir = "DOWN";
}
else{
newDir = "UP";
}
}
else{
if(dx > 0){
newDir = "RIGHT";
}
else{
newDir = "LEFT";
}
}
if (newDir != dir) {
dir = newDir;
// We only want to invalidate the view when your 'dir' value has changed.
// onDraw() will then be triggered.
invalidate();
}
}
return true;
}
答案 1 :(得分:0)
每次调用onTouchEvent
时,本地花车touchX
和touchY
都会初始化为零。这会对处理ACTION_UP
的逻辑产生影响:
dx = touchX - event.getX();
dy = touchY - event.getY();
if(Math.abs(dy) > Math.abs(dx)){
if(dy > 0){
dir = "DOWN";
} else {
dir = "UP";
}
}
dx
和dy
最终分别为-x和-y。在Math.abs()
来电之后,您实际上是在测试他们的手指是否在屏幕下方比在屏幕上方更远。
将初始向下坐标存储为成员变量,并在ACTION_DOWN
期间设置它们。