0
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 1 year has passed since last update.

【Android】Activity起動時にviewサイズを取得する

Posted at

概要

Activity起動時にviewサイズを取得する方法について解説。

方法1: onGlobalLayoutを使用

addOnGlobalLayoutListenerでレイアウト変更時のリスナーを追加。
onGlobalLayoutメソッド内でViewサイズの計測を行う処理+リスナーの削除を行う。

MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
	super.onCreate(savedInstanceState)
	setContentView(binding.root)

	binding.view.viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
		override fun onGlobalLayout() {
			Log.i("", "width:" + binding.view.width + ", height:" + binding.view.height)
			binding.view.viewTreeObserver.removeOnGlobalLayoutListener(this)
		}
	})
}

方法2: postを使用

postを用いることで、先ほどの処理より簡潔&直観的に記述できる。

MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
	super.onCreate(savedInstanceState)
	setContentView(binding.root)

	binding.view.post {
		Log.i("", "width:" + binding.view.width + ", height:" + binding.view.height)
	}
}

方法3: onWindowFocusChangedを使用

この方法だとフォーカスが変更されるたびに呼び出されるようなので、個人的にはあまりおすすめしない。

MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
	super.onCreate(savedInstanceState)
	setContentView(binding.root)
}

override fun onWindowFocusChanged(hasFocus: Boolean) {
	super.onWindowFocusChanged(hasFocus)
	Log.i("", "width:" + binding.view.width + ", height:" + binding.view.height)
}

参照

0
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
0
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?