我的活动有两个这样的图像视图,例如:example。第一次创建活动开始从屏幕的左侧向右移动(第二个图像视图不移动),并且当第一个图像视图处于第二个图像视图的范围内时,我想要检测用户是否触摸屏幕。 我尝试编写这段代码:( homeLayout是包含2张图片的布局)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ButterKnife.bind(this);
homeLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
homeLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int[] locations = new int[2];
image2.getLocationOnScreen(locations);
xImage2 = locations[0];
}
});
homeLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float xCurrentPos = image1.getLeft();
if (xCurrentPos >= xImage2 && (xCurrentPos <= xImage2 + image2.getWidth())) {
inRange = true;
}
if (inRange) {
Toast.makeText(getApplicationContext(), "In range", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Out of range", Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
我的问题是我错了image1的当前x位置,因此布尔inRange始终是假的&#34;超出范围&#34;吐司的消息。 当用户触摸屏幕时,如何获取image1的当前x位置并检查image1是否在image2的范围内? 我被卡住了,我无法解决它。
答案 0 :(得分:0)
搜索几个小时后,我设法使用以下代码检索运动图像的当前x位置:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ButterKnife.bind(this);
homeLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
homeLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int[] locations = new int[2];
image2.getLocationOnScreen(locations);
xImage2 = locations[0];
}
});
ObjectAnimator translateXAnimation = ObjectAnimator.ofFloat(image1, "translationX", image1.getLeft(), xFinalPos);
translateXAnimation.setDuration(4000);
translateXAnimation.start();
translateXAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
xCurrentPos = (float)valueAnimator.getAnimatedValue();
}
});
homeLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (xCurrentPos >= xImage2 && (xCurrentPos <= xImage2 + image2.getWidth())) {
inRange = true;
}
if (inRange) {
Toast.makeText(getApplicationContext(), "In range", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Out of range", Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
我不得不使用AnimatorUpdateListener来取回我的动态影像的当前x位置