我正在使用 android 开发游戏应用程序。
对象(一个盒子)上下滑动。它必须击中从屏幕右端朝它而来的物体(橙色和粉红色的球),这会增加他的分数。
也会有黑球(从屏幕的右端射出),他应该避免击中。
我有问题
onTouchEvent(MotionEvent me)
实现代码时的功能。
我的问题:
要使用该
onTouchEvent(MotionEvent me)
功能,我需要导入任何类吗?本教程已经声明了
onTouchEvent(MotionEvent me)
外部onCreate
方法。没关系。但是该程序没有在任何地方调用它。那么它是如何工作的呢?编写教程中提到的代码后,程序没有按预期工作。活动开始时会出现该框。但是,一旦我单击屏幕,它就会消失。可能是什么问题呢?
ActivityMain.XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/scoreLabel"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text=" : 300"
android:paddingLeft="10dp"
android:gravity="center_vertical" />
<FrameLayout
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/startLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="130dp"/>
<ImageView
android:id="@+id/box"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/box"
android:layout_gravity="center_vertical" />
<ImageView
android:id="@+id/orange"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="@drawable/orange" />
<ImageView
android:id="@+id/black"
android:layout_width="24dp"
android:layout_height="24dp"
android:src="@drawable/black" />
<ImageView
android:id="@+id/pink"
android:layout_width="16dp"
android:layout_height="16dp"
android:src="@drawable/pink" />
</FrameLayout>
</RelativeLayout>
MainActivity.java
package com.example.catcheggs1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView scoreLabel;
private TextView startLabel;
private ImageView box;
private ImageView orange;
private ImageView black;
private ImageView pink;
//Position
private int boxY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scoreLabel=(TextView)findViewById(R.id.scoreLabel);
startLabel=(TextView)findViewById(R.id.startLabel);
box=(ImageView)findViewById(R.id.box);
orange=(ImageView)findViewById(R.id.orange);
pink=(ImageView)findViewById(R.id.pink);
black=(ImageView)findViewById(R.id.black);
//Move To Out of Screen
orange.setX(-80);
orange.setY(-80);
pink.setX(-80);
pink.setY(-80);
black.setX(-80);
black.setY(-80);
//Temporary
startLabel.setVisibility(View.INVISIBLE);
boxY=500;
}
public boolean onTouchEvent(MotionEvent me)
{
if(me.getAction()==MotionEvent.ACTION_DOWN)
{
boxY -= 1 ;
}
box.setY(boxY);
return true;
}
}