从 fragment 调用时,自定义布局中的方法不起作用,但相同的方法适用于自定义样式的 (作为 xml 属性)

Method in Custom layout not working when calling from fragment, but same method works (as xml attribute) for custom styleable

提问人:sreenadh 提问时间:9/8/2023 更新时间:9/8/2023 访问量:10

问:

我正在尝试为布局文件创建一个包装类,该文件是一个 FrameLayout,其中有一个 MaterialButton 和一个 ProgressBar。我已经为“按钮文本”、“单击禁用/启用”和“显示进度条”创建了自己的样式。单击此布局后,我调用“showProgress(true)”。在“showProgress()”中,setButtonText(“”) 正在工作,但 ProgressBar 未显示。但是在XML中,当设置'app:showProgress=“true''时,它可以完美地工作。请挽救我的一天。

class ProgressButton @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null) : FrameLayout(context, attrs) {

private var binding: ButtonLayoutBinding? = null
private var mButtonText: String? = null
private var mButtonClickable: Boolean? = null
private var mOnClickListener: OnClickListener? = null
private var mShowProgress: Boolean? = null

init {
    binding =
        ButtonLayoutBinding.inflate(LayoutInflater.from(context), this, true)

    context.theme.obtainStyledAttributes(attrs, R.styleable.ProgressButton, 0, 0).apply {
        try {
            mButtonText = getString(R.styleable.ProgressButton_buttonText).also {
                setButtonText(it)
            }
            mButtonClickable = getBoolean(R.styleable.ProgressButton_buttonClickable, true).also {
                setButtonClickable(it)
            }
            mShowProgress = getBoolean(R.styleable.ProgressButton_showProgress, false).also {
                showProgress(it)
            }
        } finally {
            recycle()
        }
    }
}

fun setButtonText(buttonText: String?) {
    mButtonText = buttonText
    binding?.btnContinue?.text = buttonText
}

fun getButtonText() = mButtonText

fun setButtonClickable(buttonClickable: Boolean) {
    mButtonClickable = buttonClickable
    alpha = if (buttonClickable) 1f else 0.24f
}

fun isButtonClickable() = mButtonClickable

fun showProgress(showProgress: Boolean) {
    mShowProgress = showProgress
    if(showProgress){
        binding?.btnContinue?.isEnabled = false
        setButtonText("")
        binding?.progressBar?.visibility = VISIBLE
    }else{
        binding?.btnContinue?.isEnabled = true
        setButtonText(mButtonText)
        binding?.progressBar?.visibility = GONE
    }
}

fun isProgressShowing() = mShowProgress
override fun setOnClickListener(l: OnClickListener?) {
    super.setOnClickListener(l)
    mOnClickListener = l
}

override fun onInterceptTouchEvent(event: MotionEvent?): Boolean {
    when (event?.action) {
        MotionEvent.ACTION_DOWN -> {
            alpha = .78f
            postDelayed({
                alpha = 1f
            }, 200)
        }
    }
    return mOnClickListener != null && isButtonClickable() == true
}

override fun onFinishInflate() {
    super.onFinishInflate()
}

}

Android Kotlin android-progressbar android-framelayout android-viewbinding

评论


答: 暂无答案