Reputation: 6908
How can I use runOnUiThread
at fragment
. And how to do it in fragment?
Below is the code to do it in Activity
[email protected](java.lang.Runnable {
progressBar.visibility = View.GONE
})
Upvotes: 8
Views: 20866
Reputation: 57
This question does not make any sense to me as already stated above that all calls in the fragment will always run on main or UI thread. No need to explicitly call @runOnUithread for that matter. Its required when you are updating View from the worker thread to switch the context to UI for updating Views.
Upvotes: 0
Reputation: 564
There are two things that runOnUiThread method does.
It checks current thread
If current thread is main it executes the task immidiatly, otherwise it posing it to an activity handler
I assume, the best solution should be:
To create a new handler explicitly
Post task to a new handler
Smth like this:
private val handler = Handler(Looper.getMainLooper())
...
handler.post {
...your task...
}
Upvotes: 5
Reputation: 69709
You need to use Activity
context if you want to use runOnUiThread()
inside fragment
SAMPLE CODE
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)
}
}
SAMPLE CODE
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)
}
}
Upvotes: 10