編輯:關於 Android 程式設計
SwipeRefreshLayout 是官方提供的下拉刷新控件,用法極簡,但有幾個硬性約束需要記住。
SwipeRefreshLayout 下面只能有一個直接子節點。如果內容需要多個 View,必須先包一層 FrameLayout 或 LinearLayout,否則運行時直接崩潰。
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="MergeRootFrame" >
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</FrameLayout>
注意這裡容器是 FrameLayout,SwipeRefreshLayout 是在代碼中動態包裹或直接作為容器替換的——示例中把 findViewById(R.id.swipe_container) 對應的容器聲明為 SwipeRefreshLayout,其子節點只有一個 ListView。
setOnRefreshListener(OnRefreshListener):註冊下拉手勢的監聽;setRefreshing(boolean):手動顯示或隱藏刷新進度條;isRefreshing():查詢當前是否處於刷新狀態;setColorSchemeResource(...):設置進度條配色,最多支持四種。
public class MyActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener {
private SwipeRefreshLayout mSwipeLayout;
private ListView mListView;
private ArrayAdapter mArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
String[] strings = new String[]{"a", "b", "c", "d"};
mArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, strings);
mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
mSwipeLayout.setOnRefreshListener(this);
// 加載動畫的顏色是循環播放的,只要刷新未完成就會一直循環
// color1 > color2 > color3 > color4
mSwipeLayout.setColorSchemeResources(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
mListView = (ListView) findViewById(R.id.list);
mListView.setAdapter(mArrayAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_grid_view) {
startActivity(new Intent(MyActivity.this, GridViewTest.class));
}
return super.onOptionsItemSelected(item);
}
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mSwipeLayout.setRefreshing(false); // 停止刷新
}
}, 3000);
}
}
setDistanceToTriggerSync() 調整。shouldInterceptTouchEvent 邏輯或用 setEnabled(false) 臨時禁用。setRefreshing(false) 放在請求成功的回調裡,並在失敗分支也調一次(或放 finally)。
Android 四大數據存儲方式詳解:SharedPreferences、文件、SQLite、ContentProvider
本文大部分內容整理自《Android 開發全程實錄》,推薦有興趣的讀者閱讀原書以獲得更系統的知識。 一、SharedPreferences SharedPrefer
Android 實戰:實現圖標選中後放大浮動的效果
在瀏覽某體育門戶客戶端時,作者注意到一個有趣的交互:輕觸賽事圖標,圖標會有一個放大浮出的動畫效果。於是便仿照實現了一個,本文將分享其實現思路與代碼。 先看效果圖: 本質
startService 啟動過程源碼全解析(Android 6.0)
本文基於 Android 6.0 原始碼,剖析 startService() 背後 ActivityManagerService 所扮演的角色,並釐清 Binder、So
Android 中原生 JSON 與 Fastjson 的使用對比詳解
一、Android 原生操作 JSON核心就兩個類:JSONObject 處理對象,JSONArray 處理數組。對象轉 JSON //創建學生對象 Student st