LoginSignup
1

posted at

対象のViewが画面に表示されているかを判定する方法

はじめに

ScrollView等で対象のViewが画面に表示されたかを判定する方法を紹介します。

結論

対象のViewとScrollView(もしくは画面)のRectを取得し、対象のViewが画面のRectに含まれているかをcontainsメソッドで判定するだけです。

そもそもRectとは

Viewのleft, top, right, bottomの4つの整数座標を保持するオブジェクトです。
参考: https://developer.android.com/reference/android/graphics/Rect

手順

  1. Rect取得メソッドを作成

    fun View.getRect(): Rect {
        val array = IntArray(2)
        this.getLocationOnScreen(array)
        return Rect(array[0], array[1], array[0] + this.width, array[1] + this.height)
    }
    
  2. ViewのRectを取得

    MainActivity.kt
    val scrollViewRect = binding.scrollView.getRect()
    val targetViewRect = binding.targetView.getRect()
    
  3. 画面に表示されているかを判定

    MainActivity.kt
    if (scrollViewRect.coutains(targetViewRect)) {
        // 表示されている場合の処理
    } else {
        // 表示されていない場合の処理
    }
    

ScrollViewのsetOnScrollChangeListener等と組み合わせて使ってみてください

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
What you can do with signing up
1