android - 如何将进度条类转换为 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()
}
}
解决方案
做这样的事情
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 类,你也可以把方法放在那里
推荐阅读
- docker - 每个容器的默认内存限制
- angularjs - Umbraco cms AngularJS正则表达式不断出现
- node.js - 如何使用本地安装的 Gulp.js v4 和 `yarn --no-bin-links`?
- android - 使用后端服务器的 Google 登录失败并出现 com.google.android.gms.common.api.ApiException: 10
- python - 如何降级 Google Colab 的 Torch 版本
- assembly - 简单的引导加载程序 [实模式 - 16 位,nasm] - 尝试读取一些击键并将其打印到屏幕上
- powershell - Office 364 审核日志:Search-UnifiedAuditLog 未被识别为 cmdlet 的名称
- reactjs - 为什么我总是在 React 中得到空文件对象?
- linux - 卷初始化时 PostgreSQL 无法在 docker 上工作
- audio - 使用 mplayer 从音频流中提取冰冷的元数据(连续)