如何将加载栏添加到视图位于另一个 activity 中的适配器 class

How to add loading bar to the adapter class where the view is inside another activity

我正在尝试在适配器 class 中添加 loadingbar,其中相同的视图在 mainactivity.I 中使用 doAsync 方法加载单击 mainactivity 内的应用程序图标时的应用程序。 以下是我在 doAsync 方法中使用 loadingbar 时遇到的错误。

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

下面是适配器class

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{} 可能会解决您的问题。