使用 Kotlin 的片段中的 runOnUiThread() 方法

joh*_*o07 6 android kotlin

我怎样才能使用runOnUiThreadfragment. 以及如何在片段中做到这一点?

下面是在 Activity 中执行此操作的代码

this@MainActivity.runOnUiThread(java.lang.Runnable {
    progressBar.visibility = View.GONE
})
Run Code Online (Sandbox Code Playgroud)

Nil*_*hod 8

Activity如果你想使用runOnUiThread()内部片段,你需要使用上下文

示例代码

  class MyFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment

        activity?.runOnUiThread {
            progressBar.visibility = View.GONE
        }
        return inflater.inflate(R.layout.fragment_layout, container, false)
    }


}
Run Code Online (Sandbox Code Playgroud)

示例代码

class DepositFragment : Fragment() {

    lateinit var rootView: View
    lateinit var mContext: Context

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        (mContext as Activity).runOnUiThread { 

        }
        return inflater.inflate(R.layout.fragment_deposit, container, false)
    }
}
Run Code Online (Sandbox Code Playgroud)