android - 如何将加载栏添加到视图位于另一个活动中的适配器类
问题描述
我正在尝试loadingbar
在适配器类中添加相同的视图在doAsync
mainactivity 中。单击 mainactivity 中的应用程序图标时,我使用了加载应用程序的方法。以下是我在方法中使用 loadingbar 时遇到的错误doAsync
。
android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能接触其视图。
下面是适配器类
Adapter.kt
class Adapter(ctx: Context, private val appInfoList: ArrayList<AppInfoModel>, private val contentResolver: ContentResolver,
private val packageManager: PackageManager,
private val loadingIndicator: AVLoadingIndicatorView,
private val applicationContext: Context) : RecyclerView.Adapter<Adapter.MyViewHolder>() {
private val inflater: LayoutInflater
init {
inflater = LayoutInflater.from(ctx)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Adapter.MyViewHolder {
val view = inflater.inflate(R.layout.list_item, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: Adapter.MyViewHolder, position: Int) {
var itemView: View? = null
holder.appIcon.setImageDrawable(appInfoList[position].appIcon)
holder.appName.setText(appInfoList[position].appName)
holder.versionNumber.setText(appInfoList[position].versionNumber)
if (!appInfoList[position].isInstalled) {
holder.appInfoCard.foreground = ColorDrawable(Color.parseColor("#CCFFFFFF"))
holder.appInfoCard.isEnabled = false
holder.warningIcon.visibility = View.VISIBLE
}
holder.appInfoCard.setOnClickListener() {
Log.e("App opened", appInfoList[position].appName)
var loadingBar:AVLoadingIndicatorView= loadingIndicator.findViewById(R.id.avi)
Log.d("Loading bar", loadingBar.toString())
doAsync {
try {
loadingBar!!.setVisibility(View.VISIBLE);
LauncherUtils.setDynamicConfig(contentResolver, packageManager,applicationContext, appInfoList[position].auxName!!, appInfoList[position].packageName!!)
}
catch (e: Exception) {
Log.e("Exception-launcher", e.toString())
}
uiThread {
//loadingBar!!.setVisibility(View.INVISIBLE)
}
}
}
}
任何帮助,将不胜感激。
解决方案
就像堆栈跟踪所说的那样,您不应该从后台线程设置任何视图的可见性。移动loadingBar!!.setVisibility(View.VISIBLE);
到可能uiThread{}
会解决您的问题。
推荐阅读
- c# - 登录应用程序主屏幕后,需要在 15 分钟内提醒用户即将到来的约会(如果已安排)
- python - 按计数从熊猫数据框中提取最常见的 2 列组合
- angular - MatTableDataSource 无法读取 Angular 7 中未定义的属性“数据”
- angularjs - 仅显示日历特定日期的标题
- nginx - 在 nginx 中使用 lua 脚本发布请求处理
- azure - Azure LetsEncrypt 无法访问我的函数的 .well-known/acme-challenge
- karate - 当字符串值中包含“-”时,该值在 JSON 对象中被截断
- c# - DelegatingHandler 中的私有变量混合来自其他请求的值
- c# - 为什么在我传递(按值)字典时会生成 $ReturnValue1
> 到一个函数 - spring-boot - spring boot如何找到META-INF/spring.factories的路径