Android - Derived Style adding on to Parent style's value

   Android's style framework offers ability to override values defined by a parent style. In fact, it even lets the child style to completely remove the definition of an property from the parent's style. But there are cases when the child style would just want to add on to the values defined in the parent style. The requirement is equivalent to something like the following in a programming language like Java,

 public class Parent {

     public int getValue() {
         return 5;
     }
}

 public class Child extends Parent {

     public int getValue() {
         return 2 + super.getValue();
     }
}

    Child class's logic is able to use the Parent class's value and return an appropriate one. Unfortunately, android's xml scheme for styles doesn't support this. The only other workaround is to extract the parent style's property value at runtime and update the same. In this case, the padding values specified in the parent style (referenced via buttonBarStyle) is updated without losing the base values.

        final TypedValue value = new TypedValue();
        if ( mContext.getTheme().resolveAttribute( R.attr.buttonBarStyle, value, true ) )
        {
            int[] attrList = new int[] { android.R.attr.paddingTop, android.R.attr.paddingStart,
                    android.R.attr.paddingEnd, android.R.attr.paddingBottom };

            TypedArray a = mContext.obtainStyledAttributes(value.resourceId, attrList);
            int paddingTop = a.getDimensionPixelSize( 0, 0 );
            int paddingStart = a.getDimensionPixelSize( 1, 0 );
            int paddingEnd = a.getDimensionPixelSize( 2, 0 );
            int paddingBottom = a.getDimensionPixelSize( 3, 0 );

            a.recycle();

            paddingTop += 10;
            paddingStart += 10;
            paddingEnd += 10;
            paddingBottom += 10;
        }

No comments: