Android全局变量vs无法解析方法getApplication()

时间:2016-06-11 10:37:20

标签: android

我试图创建一个全局变量,如mutliple其他堆栈答案中所示,但是当我按照所有这些说明操作时,我得到"无法解析方法getApplication()"当试图在任何其他活动中获取或设置此变量时。我做错了什么,然后如何获取/设置此变量?这是MainActivity代码:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    private int globalVariable_Move;

    public int getGlobalVariable_Move() {
        return globalVariable_Move;
    }

    public void setGlobalVariable_Move(int value) {
        globalVariable_Move = value;
    }

这是另一个活动代码:

public class PlayActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play);

        gameView.setOnTouchListener(new View.OnTouchListener(){
            public boolean onTouch(View v, MotionEvent event){
                int tempGlobalVariableMove = ((MainActivity) this.getApplication()).getGlobalVariable_Move();
                return true;
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

您需要在Application自定义类中实现它而不是在Activity中。像这样:

public class CustomApplication extends Application {

    private Tracker mTracker;

    public Tracker getDefaultTracker() {
        if (mTracker == null) {
            mTracker = new Tracker();
        }
        return mTracker;
    }
}

从任何Activity类中获取此内容,例如:

CustomApplication app = (CustomApplication) getApplication();
app.getDefaultTracker();

或者更好地使用Singleton模式来存储全局状态和变量。