【发布时间】:2016-08-28 09:18:28
【问题描述】:
我需要一些帮助。
我在屏幕上放置了一个位图图像和 4 个导航按钮(向上、向下等)。现在我想使用这些按钮移动该图像,当然,只要按下按钮,图像就会继续移动,并且只有在用户松开手指后图像才会停止。现在我不确定下面的代码是否按预期工作,所以这就是我来这里的原因。
代码如下:
图片如下:
//SRC-Rect Values
int playerLeft, playerTop, playerBottom, playerRight;
这是图像在屏幕上的位置:
//DEST-Rect Values
int destBottom, destRight, destTop, destLeft;
这里是按钮:
//Arrow Buttons to move the player
up = (Button)findViewById(R.id.buttonUp);
right = (Button)findViewById(R.id.buttonRight);
down = (Button)findViewById(R.id.buttonDown);
left = (Button)findViewById(R.id.buttonLeft);
//Up Button
up.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
while (true){
velocityY++;
destTop += topMove;
destBottom += bottomMove;
}
}
});
//Right Button
right.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
while (true){
velocityX++;
destRight += rightMove;
destLeft += leftMove;
}
}
});
//Down Button
down.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
while (true){
velocityY--;
destTop -= topMove;
destBottom -= bottomMove;
}
}
});
//Left Button
left.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
while (true){
velocityX--;
destRight -= rightMove;
destLeft -= leftMove;
}
}
});
Velocity X 和 Y 是图像移动时的速度, 并且移动按钮的值是当按钮被触摸时它们需要移动的像素量。
//Arrow Buttons
private Button up, right, down, left;
//Movement Button Values
public static int topMove = -20;
public static int rightMove = -20;
public static int bottomMove = 20;
public static int leftMove = 20;
//Movement speed
public static int velocityX = 0;
public static int velocityY = 0;
这是 XML 布局:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonUp"
android:background="@drawable/up"
android:layout_above="@+id/buttonLeft"
android:layout_toRightOf="@+id/buttonLeft"
android:layout_toEndOf="@+id/buttonLeft" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonLeft"
android:background="@drawable/left"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonRight"
android:background="@drawable/right"
android:layout_alignTop="@+id/buttonDown"
android:layout_toRightOf="@+id/buttonDown"
android:layout_toEndOf="@+id/buttonDown" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonDown"
android:background="@drawable/down"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/buttonUp"
android:layout_alignStart="@+id/buttonUp" />
【问题讨论】:
标签: java android android-studio bitmap