android studio 游戏中通过按下不同按钮,实现飞机上下左右移动
时间: 2023-11-08 17:14:36 浏览: 35
要实现这个功能,你需要使用Android Studio中的ImageView和Button控件。首先,在xml布局文件中添加ImageView和四个Button控件,分别表示上下左右移动。例如:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/plane"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/plane"
android:layout_centerInParent="true"/>
<Button
android:id="@+id/up_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Up"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<Button
android:id="@+id/down_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Down"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
<Button
android:id="@+id/left_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Left"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"/>
<Button
android:id="@+id/right_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Right"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
```
然后,在Java代码中获取ImageView和四个Button控件,并为每个Button控件添加点击事件。在点击事件中,修改ImageView的LayoutParams,从而改变ImageView的位置。例如,向上移动时,修改ImageView的topMargin:
```java
ImageView plane = findViewById(R.id.plane);
Button up_btn = findViewById(R.id.up_btn);
Button down_btn = findViewById(R.id.down_btn);
Button left_btn = findViewById(R.id.left_btn);
Button right_btn = findViewById(R.id.right_btn);
up_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) plane.getLayoutParams();
params.topMargin -= 10;
plane.setLayoutParams(params);
}
});
down_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) plane.getLayoutParams();
params.topMargin += 10;
plane.setLayoutParams(params);
}
});
left_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) plane.getLayoutParams();
params.leftMargin -= 10;
plane.setLayoutParams(params);
}
});
right_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) plane.getLayoutParams();
params.leftMargin += 10;
plane.setLayoutParams(params);
}
});
```
这样,当用户点击不同的Button控件时,就可以实现飞机的上下左右移动了。