SwipeRefreshLayout trigger programmatically

坚强是说给别人听的谎言 提交于 2019-11-27 18:05:39
Ramz

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

 mSwipeRefreshLayout.post(new Runnable() {
        @Override
        public void run() {
            mSwipeRefreshLayout.setRefreshing(true);
        }
    });

if you simply call

 mSwipeRefreshLayout.setRefreshing(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();
   }
});

You can call onRefresh() method programmatically and then inside the method start the animation if it is not already started. See the following:

@Override
public void onRefresh() {
    if (!mSwipeRefreshLayout.isRefreshing()) mSwipeRefreshLayout.setRefreshing(true);
    //TODO
}
Goodlife

Just to force in add this two to ennable swipe gesture

swipeRefreshLayout.setOnRefreshListener(
    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.
            FetchData();
        }
    }
);
binding.swipeRefreshLayout.setRefreshing(true); // show loading 
binding.swipeRefreshLayout.post(this::updateUI); // call method
binding.swipeRefreshLayout.setOnRefreshListener(this::updateUI); // call method
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!