SwipeRefreshLayout trigger programmatically

余生颓废 提交于 2019-12-28 05:00:17

问题


Is there any way to trigger the SwipeRefreshLayout programmatically? The animation should start and the onRefresh method from the OnRefreshListener interface should get called.


回答1:


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)




回答2:


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



回答3:


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
}



回答4:


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



回答5:


binding.swipeRefreshLayout.setRefreshing(true); // show loading 
binding.swipeRefreshLayout.post(this::updateUI); // call method
binding.swipeRefreshLayout.setOnRefreshListener(this::updateUI); // call method


来源:https://stackoverflow.com/questions/24587925/swiperefreshlayout-trigger-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!