首页 > 解决方案 > 如何将进度条类转换为 kotlin 中的扩展函数?

问题描述

我有一个自定义进度条类,我想将其转换为扩展函数,以便我可以在项目中的任何位置(片段和活动)使用它而无需初始化。

我希望能够在函数中填充进度条布局,并且还希望能够关闭进度条。

我怎样才能做到这一点?

class CustomProgressDialog(context: Context) : AlertDialog(context) {
    private val messageTextView: TextView

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_loading_dialog, null)
        messageTextView = view.findViewById(R.id.message)
        setView(view)
    }

    override fun setMessage(message: CharSequence?) {
        this.messageTextView.text = message.toString()
    }

    fun showProgressDialog(message: String) {
        this.setMessage(message)
        this.setCanceledOnTouchOutside(false)
        this.setCancelable(false)
        this.show()
    }

    fun hideProgressDialog() {
        this.dismiss()
    }
}

标签: androidkotlinprogress-barextension-function

解决方案


做这样的事情

class ResultDialog(context: Context) : Dialog(context) {
    
    companion object {
            fun show(context: Context): ResultDialog {
                var resultDialog: ResultDialog? = null
                try {
                    resultDialog = ResultDialog(context)
                    resultDialog.show()
    
                } catch (ex: Exception) {
                    ex.printStackTrace()
                }
                return resultDialog!!
            }
        }
    }

然后按照以下方式调用从片段中显示此对话框

ResultDialog.show(requireContext)

你也可以有扩展功能

fun Fragment.showDialog():ResultDialog{
    return ResultDialog.show(requireContext())
}

如果你有一个基本的 Fragment 类,你也可以把方法放在那里


推荐阅读