0

我正在开发一款涉及测量加速度计值并根据这些值操纵角色位置的游戏。我只使用 X 轴。我在我的主要活动中启动了我的加速度计管理器,但我需要在另一个类中使用这些值。显然,这些值是不断变化的。如何将这些值传递给我的 GameView 类?

4

3 回答 3

0

为什么不采用 Android 方式呢?:)

当你实现一个触摸监听器时,你会做这样的事情:

myView.setOnTouchlistener(this):

这告诉视图在被触摸时给你回电。以下是如何做你自己的:

定义一个接口并使用回调让类知道值已更改。

public interface AccelerometerUpdateListener {
    void onUpdate(int arg1, string arg2); ..<----add arguments you want to pass back
}

在您的活动中:

public class MainActivity extends Activity implements AccelerometerUpdateListener {

ArrayList<AccelerometerUpdateListener > listeners = new ArrayList<AccelerometerUpdateListener >();

...


@Override
public void onCreate(Bundle savedInstanceState) 
{
    ...
    myGameClass.setResponseReceivedistener(this);
    ...
}

public void setUpdateListener(AccelerometerUpdateListener listener){
    if (!listeners.contains(listener){
        listeners.add(listener);
    }
}

public void removeUpdateListener(AccelerometerUpdateListener listener){
    if (listeners.contains(listener){
        listeners.remove(listener);
    }
}

更新值时

for (AccelerometerUpdateListener listener:listeners){
   listener.onUpdate(arg1, arg2);
}

在你的接收班:

public class MyGameClass implements AccelerometerUpdateListener {

...

@Override
public void onUpdate(int arg1, string arg2){
    // do whatever you need to do
}

全部凭记忆,如有错别字请见谅。

于 2013-02-10T22:31:40.830 回答
0

如果您使用过传感器侦听器,您可能会考虑将该逻辑移至 GameView 类。不过,如果不查看您的代码,则不能完全确定。你有样品吗?

于 2013-02-10T22:16:27.753 回答
0

您可以将它们保存为 Activity 的静态成员,或者每次它们发生变化时将它们传递给 GameView 类(新值)

于 2013-02-10T22:04:23.513 回答