johnrao07
johnrao07

Reputation: 6908

runOnUiThread() method in fragment using Kotlin

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

Answers (3)

Anup Lal
Anup Lal

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

Alexander Dadukin
Alexander Dadukin

Reputation: 564

There are two things that runOnUiThread method does.

  1. It checks current thread

  2. 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:

  1. To create a new handler explicitly

  2. Post task to a new handler

Smth like this:

private val handler = Handler(Looper.getMainLooper())
...
handler.post {
...your task...
}

https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/Activity.java#6919

Upvotes: 5

AskNilesh
AskNilesh

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

Related Questions