【问题标题】:Passing Android Acceleromter values from MainActivity to My GameView class将 Android Accelerometer 值从 MainActivity 传递到 My GameView 类
【发布时间】:2013-02-10 21:58:51
【问题描述】:

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

【问题讨论】:

    标签: android class accelerometer dynamic-variables


    【解决方案1】:

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

    【讨论】:

    • 嗯,我怎么能只有当它改变时才传递值?
    【解决方案2】:

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

    【讨论】:

    • 我用过一个传感器监听器,我想把它移过来。让我试试。不过,我仍然想知道如何正确有效地传递动态变量。
    • sensorlistener 是否只用于 GameView 类?你有什么理由在主要活动中拥有它?
    • 老实说,不,但我不确定如何在我的 GameView 类中实现它。大多数功能在我在该类中的可用范围内均不活跃。
    【解决方案3】:

    为什么不采用 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
    }
    

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

    【讨论】:

    • 我觉得你有点失去我了。愿意带我完成这个吗?
    猜你喜欢
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多