android - KOTLIN :如何使用 ViewBinding 在函数中调用视图
问题描述
因此,随着新的 Kotlin、Android Studio 更新,不可能像规范那样使用各自的 ID 调用视图,因此是视图绑定。但是,我一直在尝试使用绑定方法在函数内调用上述视图,但没有成功,因为它一直返回错误
下面是代码:
class JobActivity : AppCompatActivity() {
private val PROGRESS_MAX = 100
private val PROGRESS_START = 0
private val JOB_TIME = 4000 // ms
private lateinit var job: CompletableJob
private lateinit var binding: ActivityJobBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_job)
binding = ActivityJobBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.jobbutton.setOnClickListener {
if (!::job.isInitialized ){
initjob()
}
}
}
fun initjob(){
binding.jobbutton.setText("StartJob #1")
binding.textView2.setText("")
job= Job()
job.invokeOnCompletion {
it?.message.let {
var msg = it
if (msg.isNullOrBlank()){
msg ="Uknown cancellation Error"
}
println("${job} was cancelled. Reason:$msg")
showtoast(msg)
}
}
binding.progressBar.max= PROGRESS_MAX
binding.progressBar.progress= PROGRESS_START
}
fun showtoast(text:String){
Toast.makeText(this@JobActivity, text,Toast.LENGTH_SHORT).show()
}
}
fun ProgressBar.startJobOrCancel(job: Job) {
if (this.progress > 0) {
Log.d(TAG, "${job} is already active. Cancelling...")
resetjob()
} else {
binding.jobbutton.setText("StartJob #1")
Log.d(TAG, "coroutine ${this} is activated with job ${job}.")
}
}
错误发生在这里:
请提供准确的步骤
解决方案
@GabrielFranciss
嗯,我认为绑定对象在扩展函数之外无法识别,您必须将绑定添加为参数,或者创建一个可以在扩展函数执行和结束时调用的 lambda 函数。
fun ProgressBar.startJobOrCancel(job:Job, jobStarted: () -> Unit ) {
when {
this.progress > 0 -> {
//log
resetJob()
}
else -> {
jobFinished()
}
}
}
并使用活动/片段中的功能如下:
private var job = Job()
private var scope = CoroutineScope(Dispatchers.Default+job)
/* inside initJob() ... */
job = scope.launch(){
binding.progress.startJobOrCancel(job) {
binding.jobbutton.setText("StartJob #1")
}
}
更新(2020-11-17):
在onCreate
活动内的函数上,删除重复调用setContentView
:
...
setContentView(R.layout.activity_job) /* remove this if you're using view binding */
binding = ActivityJobBinding.inflate(layoutInflater)
setContentView(binding.root)
推荐阅读
- typescript - 可以使用枚举来键入数组
- python - ModuleNotFoundError:在heroku上运行时,django中没有名为'name_of_project'的模块
- python - 使用 python 和使用循环或 if 命令进行 Web 抓取
- sql - 透视多列中的值
- angular - 有没有办法在响应式表单上编写更少的访问器?
- angular - Ngfor和角度插值
- javascript - 使用 var 重新声明有效,但不适用于 Chrome 代码段中的 let
- mysql - 自然排序后的选择 - MySQL
- javascript - 如果 html 数据来自 API 而不是 JSON 响应,如何插入手风琴图标并进行列表切换?
- javascript - 加载时显示特定的谷歌地图信息窗口