1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

端末の向きが変わった回数をカウントする

Last updated at Posted at 2012-07-21

端末の向きが変わる度にonDestroy→onCreateの順に呼び出されることを確認する簡単なアプリケーション。

OrientationChange.java
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class OrientationChange extends Activity {
	private static int count = -1;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle bundle) {
    	super.onCreate(bundle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        count++;
        setContentView(new OrientationChangeView(this, count));
    }
    
    @Override
    public void onStop() {
    	super.onStop();
    }
}

OrientationChangeView.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class OrientationChangeView extends View {
	private int count;

	public OrientationChangeView(Context context, int count) {
		super(context);
		this.count = count;
        setBackgroundColor(Color.WHITE);
        setFocusable(true);
	}

	//描画時に呼ばれる
    @Override 
    protected void onDraw(Canvas canvas) {
        //描画オブジェクトの生成
        Paint paint=new Paint(); 
        paint.setAntiAlias(true);
        paint.setTextSize(16);
        
        //タッチXY座標の描画
        canvas.drawText("OrientationChanged>",0,20,paint);
        canvas.drawText(""+count,0,40,paint);
    }
}

端末の向きが縦→横→縦→横→…と変わる度に、向きが変わった回数がカウントされていくことを確認できた。

ただし、現状ではバックキーでホームに戻った後もアクティビティは起動したまま(メモリに残ったまま)になるためカウントがリセットされない。

キータッチイベントを検知して無理矢理リセットさせるなどの方策を採るようにしたい。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?