以编程方式触发SwipeRefreshLayout

时间:2014-07-05 15:32:25

标签: java android swiperefreshlayout

有没有办法以编程方式触发SwipeRefreshLayout?应该启动动画,并且应该调用onRefresh接口中的OnRefreshListener方法。

7 个答案:

答案 0 :(得分:129)

如果您使用的是5.0 enter image description here

中的新swipeRefreshLayout

如上图所示,您只需添加以下行以编程方式触发滑动刷新布局

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

如果您只是致电

 mSwipeRefreshLayout.setRefreshing(true);

它不会触发圆圈动画,所以通过添加上面的线你只是在UI线程中延迟,以便它显示ui线程内的圆圈动画。

致电mSwipeRefreshLayout.setRefreshing(true)OnRefreshListener未执行

为了停止循环加载动画调用mSwipeRefreshLayout.setRefreshing(false)

答案 1 :(得分:24)

为了触发SwipeRefreshLayout ,我尝试了这个解决方案:

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

现在关键部分:

swipeLayout.post(new Runnable() {
@Override public void run() {
     swipeLayout.setRefreshing(true);
     // directly call onRefresh() method 
     swipeRefreshListner.onRefresh();
   }
});

答案 2 :(得分:1)

稍微落后于线程,但是您不需要启动Runnable即可。您可以简单地触发刷新并直接在onCreate或您希望发生这种情况的任何地方调用onRefresh方法:

TLS

答案 3 :(得分:1)

只需创建一个SwipeRefreshLayout.OnRefreshListener并在需要时调用其函数onRefresh()

SwipeRefreshLayout srl;
SwipeRefreshLayout.OnRefreshListener refreshListener;

srl = (SwipeRefreshLayout)v.findViewById(R.id.swipeRefreshLayout);

refreshListener = new SwipeRefreshLayout.OnRefreshListener() {
    @Override
    public void onRefresh() {
      //Do your stuff here
    }
};
srl.setOnRefreshListener(refreshListener);

现在,只要您想手动调用它,只需通过侦听器即可调用

refreshListener.onRefresh();

答案 4 :(得分:0)

您可以通过编程方式调用onRefresh()方法,然后在方法内部启动动画(如果尚未启动)。请参阅以下内容:

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

答案 5 :(得分:-1)

强制将这两个添加到ennable滑动手势

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

答案 6 :(得分:-1)

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