0

I'm making my own custom view and having trouble accessing the layout object immediately after initializing it.

I understand the documentation says layout can be null. But is there a certain event which I can override which will tell me when it's available? I've seen answers on SO which recommend adding a ViewTreeObserver (here)

It seems weird to me that I would need a separate class to know when the layout is available. Is there another way?

Noah Santacruz
  • 460
  • 1
  • 3
  • 18

2 Answers2

1

From what I understood, there exist no such method which you can override to know when the layout is available. If you find ViewTreeObserver difficult, you can try posting a runnable in the UI Thread i.e.,

view.post(new Runnable() {
        @Override
        public void run() {
            int height = view.getHeight();
            int width = view.getWidth();
        }
    });
Fabin Paul
  • 1,701
  • 1
  • 16
  • 18
0

Basically, the initialization of the layouts occurs in onCreate() so it would be better if you try the below code in onResume() whether the custom layout is available or not.

if the custom layout is custom_layout.xml then try the below code

LayoutInflater inflater=getLayoutInflater();
View view=inflater.inflate(R.layout.custom_layout,null);
if(view!=null)
{
    //Place your code over here
}
Karthik
  • 184
  • 1
  • 3
  • 11
  • I'm not if I'm understanding correctly, but I'm trying to access the layout object from the view itself, not from the activity which is creating the view, so I don't think onCreate() or onResume() are relevant functions, right? – Noah Santacruz Nov 08 '15 at 21:05