facebook twitter hatena line email

Android/端末回転

提供: 初心者エンジニアの簡易メモ
2019年9月17日 (火) 16:04時点におけるAdmin (トーク | 投稿記録)による版 (何度かループさせる)

(差分) ←前の版 | 最新版 (差分) | 次の版→ (差分)
移動: 案内検索

回転時のライフサイクル

android/ライフサイクル

回転するときにActivityを破棄させない方法

AndroidManifest.xmlに以下を追加

<activity android:name=".MainActivity"
        android:configChanges="orientation|screenSize"></activity>

すると以下イベントは発生しなくなる。

  1. onCreate
  2. onStart
  3. onRestoreInstanceState
  4. onResume
  5. onWindowFocusChanged
  6. onPause
  7. onSaveInstanceState
  8. onStop
  9. onDestroy

代わりにonConfigurationChangedが発生するので以下コードで捕まえる

@Override
public void onConfigurationChanged(Configuration newConfig) {
       super.onConfigurationChanged(newConfig);
       Log.d(TAG, "onConfigurationChanged");
}

参考:https://qiita.com/myoshimu/items/4d891f8e0ec3abaa7662

参考:https://qiita.com/kobakei/items/5f38339dd6528fdc6b5d

onConfigurationChangedが回転前の縦幅横幅を取得してくる対策

thread処理させるとよい

   @Override
   public void onConfigurationChanged(Configuration newConfig) {
       super.onConfigurationChanged(newConfig);
       final Handler handler = new Handler();
       handler.post(new Runnable() {
           @Override
           public void run() {
               Log.i(TAG, "onConfigurationChanged width=" + imageView.getWidth());
               Log.i(TAG, "onConfigurationChanged height=" + imageView.getHeight());
           }
       });
   }

端末によってサイズが取得できない模様。

以下のように遅らせてもたまに取得できない模様・・・。

       handler.postDelayed(new Runnable() {
           @Override
           public void run() {
           @Override
           public void run() {
               Log.i(TAG, "onConfigurationChanged width=" + imageView.getWidth());
               Log.i(TAG, "onConfigurationChanged height=" + imageView.getHeight());
           }
       }, 200);

何度かループさせる

import android.os.Handler;
   private int checkCount = 0;
   private int prevHeight = 0;
   private final Handler handler = new Handler();
   private final Runnable runnable = new Runnable() {
       @Override
       public void run() {
               Log.i(TAG, "onConfigurationChanged width=" + imageView.getWidth());
               Log.i(TAG, "onConfigurationChanged height=" + imageView.getHeight());
               int height = imageView.getHeight();
               if (height != prevHeight) {
                   //LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
                   //imageView.setLayoutParams(params);
                   prevHeight = height;
               }
               if (checkCount <= 10) {
                   checkCount = checkCount + 1;
                   handler.postDelayed(runnable, 250);
               }
       }
   };
   @Override
   public void onConfigurationChanged(Configuration newConfig) {
       super.onConfigurationChanged(newConfig);
       checkCount = 0;
       handler.post(runnable);
   }