Android内置下拉刷新组件SwipeRefreshLayout
也许下拉刷新之前,你可能会使用一些第三方的开源库,例如PullToRefresh, ActionBar-PullToRefresh等待,但现在有的正式组成部分---SwipeRefreshLayout,SwipeRefreshLayout是Google在support v4 19.1版本号的library更新的一个下拉刷新组件,使用起来非常方便,能够非常方便的实现Google Now的刷新效果。
使用官方自带的控件能够保证通用性以及风格。SwipeRefreshLayout是继承ViewGroup。来实现下拉刷新,它能够包括其它组件,使用过后感觉非常easy。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="com.example.myapplication2.app.MainActivity"> <android.support.v4.widget.SwipeRefreshLayout android:id="@+id/swip" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="match_parent"> </ListView> </android.support.v4.widget.SwipeRefreshLayout> </RelativeLayout>
import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBarActivity; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity implements OnRefreshListener{ private SwipeRefreshLayout swipeRefreshLayout; Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); swipeRefreshLayout.setRefreshing(false); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swip); swipeRefreshLayout.setOnRefreshListener(this); swipeRefreshLayout.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); } @Override public void onRefresh() { handler.sendEmptyMessageDelayed(1, 5000); } }
另外,在上述onRefresh()功能被实现,以获得数据的功能和更新数据,当您完成数据更新,转让swipeRefreshLayout.setRefreshing(false);要关闭刷新。