我想请求权限并通过非阻塞函数来完成。因为我需要上下文,所以我不能从 ViewModel 调用它。如何为 fragment 提供默认 UI 范围并像这样调用挂起函数:
class MapsFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
launch {
withContext(Dispatcher.Main){
checkLocationPermission().await()
}
}
}
}
suspend fun checkLocationPermission():Boolean{...}
最佳答案
在文档中 https://developer.android.com/topic/libraries/architecture/coroutines说我可以使用 androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha01
ktx。
class MyFragment: Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewLifecycleOwner.lifecycleScope.launch {
val params = TextViewCompat.getTextMetricsParams(textView)
val precomputedText = withContext(Dispatchers.Default) {
PrecomputedTextCompat.create(longTextContent, params)
}
TextViewCompat.setPrecomputedText(textView, precomputedText)
}
}
}
关于android - 如何从 Fragment 或 Activity 调用挂起函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59043638/