有些時候,在開發app的時候,有一些特定場景需要用戶手動刷新請求更新頁面信息。例如,在開發一個新聞類軟件的時候,我們可能會需要通過下拉刷新或者上拖加載去更新信息。這時候我們就可以借助組合ListView或GirdView和SwipeRefreshLayout去完成這一功能,該控件在Support-v4.jar中有,適合安卓1.6版本及以上。
實現功能的時候需要注意,SwipeRefreshLayout作為ListView或者GirdView的父組件,更新視圖需要實現 SwipeRefreshLayout.OnRefreshListener接口,并實現其onRefresh方法,具體的更新內容建議在封裝好的方法中,在onRefresh方法中直接調用,最后記得要用setRefreshing(false)將該指示器移除。 下面這個例子是我模擬下拉刷新的實現代碼。 在這里我就簡單的按照官網實現了這個功能,有興趣的朋友可以參考一下這個鏈接安卓官網文檔
SwipeRefreshActivity.java
public class SwipeRefreshActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener{ PRivate SwipeRefreshLayout swipeRefreshLayout; private RelativeLayout parent; //該處理器用來模擬延時回收刷新指示器 private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.arg1==0){ swipeRefreshLayout.setRefreshing(false); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_swipe_refresh); initView(); initEvent(); } private void initEvent() { swipeRefreshLayout.setOnRefreshListener(this); } private void initView() { swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh); parent = (RelativeLayout) findViewById(R.id.activity_swipe_refresh); } @Override public void onRefresh() { Log.i("LOG_TAG", "onRefresh called from SwipeRefreshLayout"); // This method performs the actual data-refresh Operation. // The method calls setRefreshing(false) when it's finished. myUpdateOperation(); } private void myUpdateOperation() { Snackbar.make(parent,"refreshing.......",Snackbar.LENGTH_SHORT).setAction("Action",null).show(); Message msg = new Message(); msg.arg1 = 0; mHandler.sendMessageDelayed(msg,2000); }}<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_swipe_refresh" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.yQQ.touchtest.Activity.SwipeRefreshActivity"> <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/swiperefresh" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="match_parent" /> </android.support.v4.widget.SwipeRefreshLayout></RelativeLayout>下面內容還在創作中,請期待
新聞熱點
疑難解答