グローバル変数の定義方法

2368 ワード

woaは、私と似たような需要のある問題を見つけて、その下で良い解決策を提供して、私が前に考えたように、この方法は便利そうです.
The more general problem you are encountering is how to save stateacross several Activities and all parts of your application. A staticvariable (for instance, a singleton) is a common Java way of achievingthis. I have found however, that a more elegant way in Android is toassociate your state with the Application context.
--アプリケーション全体で使用するにはjavaでは静的変数が一般的ですが、androidではApplication contextを使用するより優雅な方法があります.
As you know, each Activity is also a Context, which is informationabout its execution environment in the broadest sense. Your applicationalso has a context, and Android guarantees that it will exist as asingle instance across your application.
--各ActivityはContextであり、実行時のステータスの一部が含まれており、androidはsingle instanceであることを保証しています.
The way to do this is to create your own subclass of android.app.Application,and then specify that class in the application tag in your manifest.Now Android will automatically create an instance of that class andmake it available for your entire application. You can access it fromany context using the Context.getApplicationContext() method (Activityalso provides a method getApplication() which has the exact sameeffect):
--あなた自身のandroidを作成する方法です.app.Applicationのサブクラス、manifestでこのクラスを説明します.これはandroidがグローバルで利用可能なインスタンスを構築し、Contextを他の場所で使用することができます.getApplicationContext()メソッドは、このインスタンスを取得し、そのステータス(変数)を取得します.
例を示します.
class MyApp extends Application {

  private String myState;

  public String getState(){
    return myState;
  }
  public void setState(String s){
    myState = s;
  }
}

class Blah extends Activity {

  @Override
  public void onCreate(Bundle b){
    ...
    MyApp appState = ((MyApp)getApplicationContext());
    String state = appState.getState();
    ...
  }
}

This has essentially the same effect as using a static variable orsingleton, but integrates quite well into the existing Androidframework. Note that this will not work across processes (should yourapp be one of the rare ones that has multiple processes).
--この効果は、静的変数を使用するのと同じですが、androidのアーキテクチャアーキテクチャに適しています.
テキストリンク:http://stackoverflow.com/questions/708012/android-how-to-declare-global-variables