0

I would like to use the viewTreeObserver so I can listen to when the layout is finished loading and then get coordinates of some views in that layout. I followed the advice here: How to get the absolute coordinates of a view

I translated the code to Kotlin, however the function in the listener is never being called. My code is very simple:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val layoutInflater: LayoutInflater = LayoutInflater.from(applicationContext)
        val view: View = layoutInflater.inflate(R.layout.activity_main, null)

        view.viewTreeObserver.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                Log.d("TAG", "Called!!!")
            }
        })

       setContentView(R.layout.activity_main)
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
sir-haver
  • 3,096
  • 7
  • 41
  • 85

1 Answers1

2

The view you inflate and get the viewTreeObserver from is never added to the hierchy. So this observer never calls any events.

When you call setContentView(R.layout.activity_main) a new view is inflated which never had the listener added.

You could use setContentView(view) instead.

RobCo
  • 6,240
  • 2
  • 19
  • 26
  • Oh I'm sorry but then the layout is empty, although the view object should have been inflated with the layout, so why is it empty? Thanks – sir-haver Dec 20 '19 at 09:22
  • I'm not sure. One think I notice now is you use LayoutInflater.from(applicationContext) while you don't want to use the application context here because it should know about the activity. So change that to LayoutInflater.from(this). If that doesn't work make sure the activity_main.xml is correct, check the LogCat for warnings and errors or put a breakpoint after the View is inflated and check it has all the correct children and whatnot. – RobCo Dec 20 '19 at 09:29
  • Yes now it's working thanks Rob, honestly I don't understand the difference between applicationContext and this, but I will research it further thanks a lot! – sir-haver Dec 20 '19 at 09:35