<android.support.v4.widget.SwipeRefreshLayout android:layout_width="match_parent" android:layout_height="match_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:id="@+id/swipe"> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Random number:" android:id="@+id/lbl"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rndNum" android:layout_toRightOf="@id/lbl"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/lbl" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:text="Swipe to Refresh" style="@android:style/TextAppearance.Medium"/> </RelativeLayout> </ScrollView> </android.support.v4.widget.SwipeRefreshLayout>
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.widget.TextView; public class MainActivity extends Activity { private SwipeRefreshLayout swipe_container; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); swipe_container = (SwipeRefreshLayout) findViewById(R.id.swipe_container); tv = (TextView)findViewById(R.id.textView1); swipe_container.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light); swipe_container.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { tv.setText("正在刷新"); new Handler().postDelayed(new Runnable() { @Override public void run() { tv.setText("刷新完成"); swipe_container.setRefreshing(false); } }, 5000); } }); } }
在listView滑动的时候会有些问题,增加listview的一个监听,如下:
listView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int i) { } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (firstVisibleItem == 0) swipe_container.setEnabled(true); else swipe_container.setEnabled(false); } });