Search code examples
androidviewlayoutparams

Proper Way of Changing View Properties at runtime


So i have a view which is inflated via Xml. That view has a subView, which i need to set a marginTop with a dynamic value like this:

toolbar.getHeight() - 100

For this reason, i cannot set it to xml. I could do this:

?attr/actionBarSize

but i need specifically toolbar.getHeight() - 100

What is the proper way of accomplish this? I am doing it in the onCreate of the activity, i set a viewTreeObserver.addOnGlobalLayoutListener for that view, get the layoutParameters and add a margin.

Is this the right way to do this? The way i see it, the view is drawn, and when i run some code inside viewTreeObserver of that view, the view must be redrawn again. Is there a way of avoid this double rendering without setting a custom view?


Solution

  • Inside of onCreate() you can look up the value for this attribute in the current context:

    int[] attrIds = new int[1]{ R.attr.actionBarSize };
    TypedArray a = obtainStyledAttributes(attrIds);
    // first argument is index in attrIds, second argument is
    // a default value to return if not found
    int actionBarSize = a.getDimensionPizelSize(0, 0);
    a.recycle();
    // do something with actionBarSize