2

アクティビティで onCreate() を扱うのに大きな問題があります。スレッドが言ったように、メイン アクティビティの onCreate() メソッドでコードの一部を 1 回しか実行できません。そのため、そのスレッドの手順に従い、次のことを行います。

/*I've updated the code to SharePreferences version*/

public class MyApp extends Activity {
   private static RMEFaceAppActivity instance;
   private boolean wascalled = false;

   private SharedPreferences sharedPreferences;       
   private SharedPreferences.Editor editor; 


   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

     setContentView(R.layout.main);

      //initiate some buttons here

     sharedPreferences = this.getSharedPreferences("test",0);  
     editor = sharedPreferences.edit();  

    if(sharedPreferences.getString("wascalled", "false").equalsIgnoreCase("false"))
    {
        //work can only be done once
        editor.putString("wascalled", "true");
        editor.commit();
    }
        //set buttons to listener methods

   }

   void onClick(View arg0)
   {
      if(arg0.getId() == R.id.button1)
      {
         Intent intent = new Intent(this, MyChildApp.class);
         startActivity(intent);
      }
   }

}

MyChildApp クラスではfinish()、作業が完了したときに呼び出します。ただし、フィールドwascalledは常に false です。onCreate()から戻ったときに が 2 回目に実行されるときはMyChildAppwascalledすでに true に設定する必要があると思います。しかし、そうではありません。そして、メソッド内の if 文内のコードは、onCreate()から戻るたびに実行されMyChildAppます。

これについて誰かアドバイスはありますか?よろしくお願いします。

4

3 に答える 3

1

SharedPreferencesを定義0/falseし、wascall() が呼び出されなかったことを示す値を最初に格納します。

ここで、wasCalled が初めて呼び出されたときに、この SharedPreference 変数の値を に更新します1/true

次回のonCreate()実行時に、SharedPreference の変数の値を確認し、値が 1/true の場合は再度実行しないでください。

SharedPreferences を実装するコード:

final String PREF_SETTINGS_FILE_NAME = "PrefSettingsFile";
int wasCalledValue;

onCreate() {

....


SharedPreferences preferences = getSharedPreferences(PREF_SETTINGS_FILE_NAME, MODE_PRIVATE);
wasCalledValue=  preferences.getInt("value", 0); 

if(wasCalledValue == 0)
{
// execute the code
//now update the variable in the SharedPreferences
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("value", 1);
editor.commit();

}

else if(wasCalledValue == 1)
{
//skip the code
}

} // end of onCreate()
于 2012-08-16T15:52:08.663 に答える
0

wascalledActivity インスタンスの一部であるため、常に false になります。それはあなたの活動で宣言されました:

private boolean wascalled = false;

アクティビティが再作成されると、すべてのインスタンス変数がデフォルト値に初期化されるため、 always が取得されますfalse

そのスレッドwascalledのコードに注意を払うと、 が Activity のクラスではなく、別のクラスの一部であることがわかります。

if (!YourApplicationInstance.wasCalled) {
}

この具体的な例では、変数YourApplicationInstanceの状態を保持する別のクラスです。wascalled

于 2012-08-16T15:47:57.760 に答える
0

MyChildApp から戻ると、myApp が再作成されるため、onCreate が再度呼び出され、変数が再度初期化されます (これが、wascall が常に false である理由です)。

考えられる解決策の 1 つは、wascall 状態を SharePreferences に保存することです。

于 2012-08-16T15:46:22.160 に答える