使用这个类并在初始化部分自定义
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"
}}
我有 Java 的实现方式。哪个正在工作
您必须读取背景、大小等属性。在未设置的情况下设置一些默认值并将这些设置为按钮,如下面的代码
读取属性
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();
}
设置成这样
this.setTextColor(textColor);
this.setAllCaps(false);
this.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
((Button)this).setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
设置自定义背景
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);