0

I am having a problem using vector drawables, although I found out that you can support vector by using the

app:srcCompat:"@/drawable/your_icon"

and this works fine, but I want to put the icon on top of the text of a button, but I can't use the drawableTop attribute on my button. So is creating custom attribute possible?

1 Answer 1

4

Try this.

public class CustomButtonForDrawableTop extends AppCompatButton{
public CustomButtonForDrawableTop(Context context){
    super(context);
}

public CustomButtonForDrawableTop(Context context, AttributeSet attrs){
    super(context,attrs);
    initAttrs(context,attrs);
}

public CustomButtonForDrawableTop(Context context, AttributeSet attrs, int defStyleAttr){
    super(context,attrs,defStyleAttr);
    initAttrs(context,attrs);
}



void initAttrs(Context context, AttributeSet attrs) {
    if(attrs != null){
        TypedArray attributeArray = context.obtainStyledAttributes(
                attrs,
                R.styleable.CustomButtonForDrawableTop);

        Drawable drawableTop = null;

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            drawableTop = attributeArray.getDrawable(R.styleable.CustomButtonForDrawableTop_drawableTopCompat);
        } else {
            final int drawableTopId =attributeArray.getResourceId(R.styleable.CustomButtonForDrawableTop_drawableTopCompat, -1);

            if(drawableTopId != -1)
                drawableTop = AppCompatResources.getDrawable(context,drawableTopId);
        }
        setCompoundDrawablesWithIntrinsicBounds(null, drawableTop, null, null);
        attributeArray.recycle();
    }
}
}

then create attrs.xml on values

<resources>
<declare-styleable name="CustomButtonForDrawableTop">
    <attr name="drawableTopCompat" format="reference"/>
</declare-styleable>
</resources>

here's how you call it

 <com.example.user.project.CustomButtonForDrawableTop
            app:drawableTopCompat="@drawable/ic_people_black_48px"
            android:layout_margin="5dp"
            android:drawableTint="@color/myColor"
            android:id="@+id/btnStaff"
            android:layout_width="115dp"
            android:layout_height="115dp"
            android:elevation="4dp"
            android:text="Staff"
            android:textAllCaps="false"
            android:textColor="@color/myColorWhite"
            android:shadowColor="@color/myColorActionBar"
            android:background="@drawable/custom_button_rounded8"
            app:layout_flexBasisPercent="@fraction/fraction48percent"/>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.