Question

So i have two custom views. I need to know the pixel dimensions of my custom view and i got it the following way:

    protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld)
    {
        width_dimension = xNew; // << this is the field i need to share
        super.onSizeChanged(xNew, yNew, xOld, yOld);
    }

I have another custom view, where i need to pass the field "width_dimension". What is the proper way to do this? I tried passing the info in the onCreate() method of my activity but it is called before the onSizeChanged() of my custom view so the field is undefined. I also tried passing in the onSizeChanged() method (above) but my OTHER custom view wasn't instantiated by the xml layout yet (threw a null pointer exception).

Is overriding the onSizeChanged() method the proper way to determine a views width (it is set to wrap_content in xml)? And how can i share this information to another custom view?

Sorry if this question is not very clear. It's hard to explain and the problem i'm facing is i need to know WHEN all my custom views have been instantiated and laid out so i can exchange dimension information (determined at runtime) between them.

Was it helpful?

Solution

You could use dimensions see here: http://developer.android.com/guide/topics/resources/more-resources.html#Dimension are useful if you have the custom views implemented in xml.. you could also load the dimension in code like this:

Resources res = context.getResources(); // you can use application or activity context for this
float customWidth = res.getDimension(R.dimen.custom_width);

I hope it helps!

EDIT

So it seems that this helped:

yourlayout.getViewTreeObserver().addOnGlobalLayoutListener(ViewTreeObserver.OnGl‌​obalLayoutListener yourCustomListener); 

The callback will get called after the view will get measured and draw. Also I would suggest to remove the listener from the view once the callback is called to avoid useless calls.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top