我一直在尝试构建一个简单的益智应用程序,更多地只是为了向自己证明我可以做到这一点。这是一个简单的 9 块拼图,缺少一块。与丢失的瓷砖相邻的瓷砖可以移动到该插槽中。
我试图做的是为瓷砖使用 9 个图像视图的网格布局。每当要移动图块时,我都会实例化第十个图像视图,将图块的图像源和位置传递给它。然后将原始图块设置为不可见,移动图块移动到新位置,此时它将此数据传递给接收图块并变为不可见。
首先我找到两个相邻的imageViews之间的偏移量:
int startPosition1[] = new int[2];
topLeft.getLocationOnScreen(startPosition1);
int startPosition2[] = new int[2];
topCenter.getLocationOnScreen(startPosition2);
final int separation = startPosition2[1] - startPosition1[1];
然后,在 OnClickListener 中,我检查移动是否有效并调用我创建的方法来执行移动(moveme):
topLeft.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int thisLocation[] = new int[2];
v.getLocationOnScreen(thisLocation);
int invisibleLocation[] = new int[2];
findViewById(theInvisible).getLocationOnScreen(invisibleLocation);
if ((thisLocation[0] - invisibleLocation[0]) == 0)
{
if ((thisLocation[1] - invisibleLocation[1]) == separation)
{
Toast.makeText(getApplicationContext(), R.string.boldly ,Toast.LENGTH_LONG).show();
moveMe(thisLocation, "translationY", (0-separation), v);
}
else if((invisibleLocation[1] - thisLocation[1]) == separation)
{
Toast.makeText(getApplicationContext(), R.string.boldly, Toast.LENGTH_LONG).show();
moveMe(thisLocation, "translationY", separation, v);
}
}
else if ((thisLocation[1] - invisibleLocation[1]) == 0) {
if ((thisLocation[0] - invisibleLocation[0]) == separation) {
Toast.makeText(getApplicationContext(), R.string.boldly, Toast.LENGTH_LONG).show();
moveMe(thisLocation, "translationX", (0 - separation), v);
} else if ((invisibleLocation[0] - thisLocation[0]) == separation) {
Toast.makeText(getApplicationContext(), R.string.boldly, Toast.LENGTH_LONG).show();
moveMe(thisLocation, "translationX", separation, v);
}
}
else
{
Toast.makeText(getApplicationContext(), R.string.illogical, Toast.LENGTH_LONG).show();
}
}
});
这是 moveMe 方法:
void moveMe( int[] thisLocation, String direction, int separation, View v)
{
Log.i(TAG, "Entere mover");
ImageView mover = (ImageView) findViewById(R.id.mover);
ImageView destination = (ImageView) findViewById(getTheInvisible());
mover.setContentDescription(v.getContentDescription());
setView(mover);
mover.setX(thisLocation[0]);
mover.setY(thisLocation[1]);
Log.i(TAG, "relocated mover");
mover.setVisibility(View.VISIBLE);
v.setVisibility(View.INVISIBLE);
v.setClickable(false);
setTheInvisible(v);
Log.i(TAG, "Swapped visibilities");
ObjectAnimator test = ObjectAnimator.ofFloat(mover, direction, separation);
test.setDuration(1000);
test.setRepeatCount(0);
test.start();
Log.i(TAG, "animation complete");
destination.setContentDescription(mover.getContentDescription());
setView(destination);
destination.setVisibility(View.VISIBLE);
destination.setClickable(true);
mover.setVisibility(View.INVISIBLE);
Log.i(TAG, "Swapped views with destination");
}
据我所知,这个方法甚至没有被调用。此外,任何符合调用此方法的条件的图块也不会发出它的 toast 消息。最后,我注意到任何从空白图块沿 x 或 y 轴直接设置两个空间的图块也不会显示其文本。提前致谢。