我正在尝试制作一个简单的拖放游戏。为了不必在每个视图上分别设置setTouchListeners,我在布局中进行设置。
我要用于过滤掉未放置在对象本身上的触摸的方法是询问视图的矩形是否包含我分别从event.getX()和Y获得的坐标。
我已经打印出一个烤面包,以确保它确实包含坐标,并且确实如此。
但是该事件并未注册为真。
能请你帮忙吗?
import android.graphics.Rect;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class GameActivity extends AppCompatActivity {
private static final String TAG = "GameActivity";
private float x;
private float y;
private Integer currentXInt;
private Integer currentYInt;
ConstraintLayout mLayout = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
mLayout = findViewById(R.id.GameActivityID);
final View viewTest = findViewById(R.id.viewTest);
mLayout.setOnTouchListener(new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event)
{
Rect viewTestRect = new Rect(viewTest.getLeft(),viewTest.getRight(),viewTest.getTop(),viewTest.getBottom());
x = event.getX();
y = event.getY();
currentXInt = Math.round(event.getX());
currentYInt = Math.round(event.getY());
if(viewTestRect.contains(currentXInt,currentYInt)){
viewTest.setX(x);
viewTest.setY(y);
}
Toast.makeText(getApplicationContext(),"view X: " + currentXInt.toString()+" view Y: " + currentYInt.toString()+ "\nRect: " +
viewTestRect + "\nBool: " + viewTestRect.contains(currentXInt,currentYInt),Toast.LENGTH_LONG ).show();
Log.d(TAG, "onTouch layout");
return true;
}
});
}
}
干杯。
答案 0 :(得分:0)
一个简单的菜鸟错误,我将.get ___()方法的顺序错误,应该是:
Rect viewTestRect = new Rect(viewTest.getLeft(),viewTest.getTop(),viewTest.getRight(),viewTest.getBottom());
现在一切正常。