Is there any way to trigger the SwipeRefreshLayout programmatically? The animation should start and the onRefresh method from the OnRefreshListener interface should get called.
if you are using the new swipeRefreshLayout intoduced in 5.0 
As the image shown above you just need to add the following line to trigger the swipe refresh layout programmatically
in Java:
 mSwipeRefreshLayout.post(new Runnable() {
     @Override
     public void run() {
         mSwipeRefreshLayout.setRefreshing(true);
     }
 });
on in Kotlin:
mSwipeRefreshLayout.post { mSwipeRefreshLayout.isRefreshing = true }
if you simply call in Java:
 mSwipeRefreshLayout.setRefreshing(true);
or in Kotlin
 mSwipeRefreshLayout.isRefreshing = true
it won't trigger the circle to animate, so by adding the above line u just make a delay in the UI thread so that it shows the circle animation inside the ui thread.
By calling mSwipeRefreshLayout.setRefreshing(true) the OnRefreshListener will NOT get executed
In order to stop the circular loading animation call mSwipeRefreshLayout.setRefreshing(false)
In order to trigger SwipeRefreshLayout I tried this solution:
SwipeRefreshLayout.OnRefreshListener swipeRefreshListner = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.i(TAG, "onRefresh called from SwipeRefreshLayout");
            // This method performs the actual data-refresh operation.
            // The method calls setRefreshing(false) when it's finished.
            loadData();
        }
    };
Now key part:
swipeLayout.post(new Runnable() {
@Override public void run() {
     swipeLayout.setRefreshing(true);
     // directly call onRefresh() method 
     swipeRefreshListner.onRefresh();
   }
});
                        Bit late to the thread, but you do not need to launch a Runnable to do this. You can simply trigger the refresh and call your onRefresh method directly in onCreate, or wherever you want this to happen:
class MyFragment: SwipeRefreshLayout.OnRefreshListener {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
    }
    fun initViews() {
        swipe_refresh_layout?.apply {
            setOnRefreshListener(this@MyFragment)
            isRefreshing = true
            onRefresh()
        }
    }
    override fun onRefresh() {
        // Do my refresh logic here
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With