要更改函数中的线程,我使用 CoroutineScope 或 withContext。我不知道有什么区别,但是使用 CourineScope 我也可以使用处理程序。
例子:
private fun removeViews(){
CoroutineScope(Main).launch(handler){
gridRoot.removeAllViews()
}
}
private suspend fun removeViews(){
withContext(Main){
gridRoot.removeAllViews()
}
}
Run Code Online (Sandbox Code Playgroud)
我从一个在后台线程 (IO) 上工作的协程调用这个函数。哪个比另一个更合适?
我有两个EditText输入字段 ( inputType="phone"),一个用于 IP 地址,一个用于端口号。我想以字符串形式获取这两个值。
val ip : String = findViewById<EditText>(R.id.ip).toString()
val port: String = findViewById<EditText>(R.id.port).toString()
println("IP AND PORT: $ip : $port")
Run Code Online (Sandbox Code Playgroud)
输出类似于:androidx.appcompat.widget.AppCompatEditText...
我想设置文本:车站 1、车站 2、车站 3...
如果我有这样的代码(框架的类型为 ScrollView),我会收到警告:“不要连接与 setText 显示的文本。使用带有占位符的资源字符串。”
for(i in 1..10){
frame.stationTextView.text = "Station $i"
}
Run Code Online (Sandbox Code Playgroud)
但如果我这样做,我就不会收到警告。
for(i in 1..10){
val str = "Station $i"
frame.stationTextView.text = str
}
Run Code Online (Sandbox Code Playgroud)
第二个例子对我来说似乎多余,但警告消失了。哪一个是正确的,也可能都不正确。我不确定如何使用索引正在变化的资源字符串。