1. 程式人生 > >Android自帶重新整理外掛SwipeRefreshLayout詳解

Android自帶重新整理外掛SwipeRefreshLayout詳解

SwipeRefreshLayout是Android中自帶的一款重新整理用的外掛,使用起來十分的方便,簡單。
SwipeRefreshLayout的使用分為三步:
1. 在佈局中需要使用重新整理的佈局外部加一個SwipeLayout。
2. 實現SwipeRefreshLayout.OnRefreshListener中的onRefresh()方法。
3. 在onRefresh()中進行邏輯處理,SwipeRefreshLayout.setRefreshing(false);結束重新整理。
下面給出一個例項:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <android.support.v4.widget.SwipeRefreshLayout android:id="@+id/swipe_ly" 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> </LinearLayout>
public class MainActivity
extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
private ListView listView; private SwipeRefreshLayout swipeRefreshLayout; private ArrayList<String> list; private ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); list=new ArrayList<>(); list.add("hanking 1"); list.add("hanking 2"); list.add("hanking 3"); list.add("hanking 4"); list.add("hanking 5"); list.add("hanking 6"); listView=(ListView)findViewById(R.id.listView); adapter=new ArrayAdapter<>(this, android.R.layout.simple_expandable_list_item_1, list); listView.setAdapter(adapter); swipeRefreshLayout=(SwipeRefreshLayout)findViewById(R.id.swipe_ly); swipeRefreshLayout.setOnRefreshListener(this); swipeRefreshLayout.setColorSchemeColors(R.color.colorAccent); } @Override public void onRefresh() { list.add("good"); list.add("hello"); adapter.notifyDataSetChanged(); swipeRefreshLayout.setRefreshing(false); } }

上面程式碼中swipeRefreshLayout.setOnRefreshListener(this);是給SwipeRefreshLayout設定監聽器,如果沒有的話那麼重新整理時就不會執行onRefresh(){}方法,重新整理就會一直進行。
swipeRefreshLayout.setColorSchemeColors(R.color.colorAccent);這個是設定重新整理時旋轉圖示的式樣。