android自带下拉刷新SwipeRefreshLayout
也是一个布局容器,只有一个子组件,类似scrollView
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:id="@+id/swipeLayout" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </android.support.v4.widget.SwipeRefreshLayout>
public class MainActivity extends AppCompatActivity { SwipeRefreshLayout swipeRefreshLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipeLayout); swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.colorPrimary, R.color.colorPrimaryDark); swipeRefreshLayout.setSize(SwipeRefreshLayout.DEFAULT);; swipeRefreshLayout.setProgressViewOffset(true, 0, 200); swipeRefreshLayout.setProgressViewEndTarget(true, 100); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Thread(new Runnable() { @Override public void run() { try { sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } mHandler.sendEmptyMessage(1); } }).start(); } });} //handler @SuppressLint("HandlerLeak") Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: Toast.makeText(MainActivity.this, "刷新成功", Toast.LENGTH_SHORT).show(); swipeRefreshLayout.setRefreshing(false); break; } } }; }
属性一运行便知道,在监听器里执行刷新任务,用handler通知主线程