如何创建自定义按钮类并添加默认功能

huangapple go评论83阅读模式
英文:

How to create custom button class and add default features

问题

我正在尝试创建一个自定义按钮类但是无法设置默认的文本大小和背景

**ButtonGray.kt**

class ButtonGray(context: Context?, attrs: AttributeSet?) : androidx.appcompat.widget.AppCompatButton(context, attrs) {

    init {
        textSize = 30.0F
        background = R.drawable.bg_btn_gray
    }
}

[ButtonGray.kt][1]


[默认情况下无法分配文本大小。][2]


编辑

我尝试了这段代码

background = context?.getDrawable(R.drawable.bg_btn_gray)

没有报错但默认情况下它不起作用

[enter image description here][3]


  [1]: https://i.stack.imgur.com/hwOsV.png
  [2]: https://i.stack.imgur.com/qyIs5.png
  [3]: https://i.stack.imgur.com/3HWX6.png
英文:

I'm trying to create a custom button class but I can't set the default text size and background.

ButtonGray.kt

class ButtonGray(context: Context?, attrs: AttributeSet?) : androidx.appcompat.widget.AppCompatButton(context, attrs) {

    init {
        textSize = 30.0F
        background = R.drawable.bg_btn_gray
    }
}

ButtonGray.kt

text size cannot be assigned by default.

EDIT:

I try this code:

 background = context?.getDrawable(R.drawable.bg_btn_gray)

Does not give an error. But it didn't work by default.

enter image description here

答案1

得分: 1

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatButton
import androidx.core.content.ContextCompat

class ButtonGray : AppCompatButton {
    constructor(context: Context) : super(context) {
        init()
    }

    constructor(
        context: Context,
        attrs: AttributeSet?
    ) : super(context, attrs) {
        init()
    }

    constructor(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int
    ) : super(context, attrs, defStyleAttr) {
        init()
    }

    private fun init() {
        width = resources.getDimension(R.dimen.your_dimen).toInt()
        height = resources.getDimension(R.dimen.your_dimen).toInt()
        setBackgroundColor(ContextCompat.getColor(context, R.color.yourColor))
    }
}
英文:
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatButton
import androidx.core.content.ContextCompat
   
class ButtonGray : AppCompatButton {
    constructor(context: Context) : super(context) {
        init()
    }

    constructor(
        context: Context,
        attrs: AttributeSet?
    ) : super(context, attrs) {
        init()
    }

    constructor(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int
    ) : super(context, attrs, defStyleAttr) {
        init()
    }

    private fun init() {

        width= resources.getDimension(R.dimen.your_dimen).toInt()
        height= resources.getDimension(R.dimen.your_dimen).toInt()

        setBackgroundColor(ContextCompat.getColor(context,R.color.yourColor))

    }
}

答案2

得分: 1

这是我在Kotlin中创建自定义按钮的方法。

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatButton
import com.urfeed.R

class PrimaryButton : AppCompatButton {

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    private fun init() {
        this.background = context.getDrawable(R.drawable.gradient)
        this.textSize = 10f
        this.setTextColor(context.getColor(R.color.white))
    }

    fun turnIntoPrimary(text: String) {
        this.text = text
        this.background = context.getDrawable(R.drawable.primary_bkg_drawable)
        postInvalidate()
    }

    fun turnIntoSecondary(text: String) {
        this.text = text
        this.background = context.getDrawable(R.drawable.secondary_bkg_drawable)
        postInvalidate()
    }
}

用法:

button.turnIntoPrimary("Primary")

button.turnIntoSecondary("Secondary")
英文:

Here is how I have a created a custom button in Kotlin.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatButton
import com.urfeed.R


class PrimaryButton : AppCompatButton {

    constructor(context: Context) : super(context){
        init()
    }

    constructor(
        context: Context,
        attrs: AttributeSet?
    ) : super(context, attrs) {
        init()
    }

    constructor(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int
    ) : super(context, attrs, defStyleAttr) {
        init()
    }


    private fun init() {
        this.background = context.getDrawable(R.drawable.gradient)
        this.textSize = 10f
        this.setTextColor(context.getColor(R.color.white))
    }

    fun turnIntoPrimary(text: String){
        this.text = text
        this.background = context.getDrawable(R.drawable.primary_bkg_drawable)
        postInvalidate()
    }

     fun turnIntoSecondary(text: String){
        this.text = text
        this.background = context.getDrawable(R.drawable.secondary_bkg_drawable)
        postInvalidate()
    }

}

<!-- end snippet -->

Usage:

button.turnIntoPrimary("Primary")

button.turnIntoSecondary("Secondary")

答案3

得分: 0

使用这个类并在初始化部分进行自定义

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);
英文:

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 = &quot;Hello&quot;
}}

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 &gt; 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);

huangapple
  • 本文由 发表于 2020年7月27日 22:13:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63117205.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定