Use this class and customize in init section
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatButton
class ButtonGray(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : AppCompatButton(context, attrs, defStyleAttr){
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) {
init()
}
constructor(context: Context) : this(context, null, 0) {
init()
}
init {
setBackgroundColor(R.drawable.bg_btn_gray)
textSize = 30.0F
text = "Hello"
}}
I have Java Way of implementation. which is working
You have to read attributes for background, size etc. Put some default value in case not set and set these to button like below code
Read Attributes
TypedArray attributes = context.getTheme().obtainStyledAttributes(attributeSet, R.styleable.IGButton,0,0);
try {
setType(attributes.getInt(R.styleable.IGButton_buttonType,0));
setiConPos(attributes.getInt(R.styleable.IGButton_iconPos,0));
borderWidth = attributes.getInt(R.styleable.IGButton_borderWidth, Constants.BUTTON_BORDER_WIDTH);
radius = attributes.getInt(R.styleable.IGButton_borderRadius, Constants.BUTTON_BORDER_RADIUS);
fontSize = attributes.getInt(R.styleable.IGButton_fontSizeSP, Constants.BUTTON_TEXT_FONT_SIZE);
int drawableId = attributes.getResourceId(R.styleable.IGButton_smallIcon, 0);
if(drawableId > 0) {
icon = getResources().getDrawable(drawableId, context.getTheme());
}
}
finally {
attributes.recycle();
}
Set it like
this.setTextColor(textColor);
this.setAllCaps(false);
this.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
((Button)this).setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
Set Custom Background
GradientDrawable drawable = new GradientDrawable();
drawable.setColor(backgroundColor);
drawable.setCornerRadius(radius);
drawable.setStroke(borderWidth, borderColor);
this.setBackground(drawable);
StateListAnimator animator = AnimatorInflater.loadStateListAnimator(context,
R.animator.button_animation_set);
((Button)this).setStateListAnimator(animator);