首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android PullToRefresh 框架實現 ListView JSON 資料解析與上拉載入下拉刷新

     編輯:程式設計綜合問答

在 Android 專案中使用 PullToRefresh 框架(如 Chris Banes 版本)實現 ListView 的下拉刷新與上拉載入,並解析 JSON 資料綁定顯示,是常見需求。以下為關鍵實作步驟:

1. 引入框架與佈局

在 build.gradle 加入依賴(或手動匯入 Library 專案),佈局檔使用 PullToRefreshListView 取代原生 ListView。

<com.handmark.pulltorefresh.library.PullToRefreshListView
    android:id="@+id/pull_refresh_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    ptr:ptrMode="both" />

2. 設定監聽器與資料載入邏輯

PullToRefreshListView mPullListView = findViewById(R.id.pull_refresh_list);
mPullListView.setMode(Mode.BOTH);
mPullListView.setOnRefreshListener(new OnRefreshListener2() {
    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        loadData(true);  // 重新載入第一頁
    }
    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        loadData(false); // 載入下一頁
    }
});

3. JSON 解析與適配器更新

在 loadData() 中發送網路請求,解析 JSON 陣列轉為實體物件清單,更新 BaseAdapter 並呼叫 onRefreshComplete()。

private void parseJson(String json) {
    try {
        JSONArray array = new JSONArray(json);
        for (int i = 0; i < array.length(); i++) {
            JSONObject obj = array.getJSONObject(i);
            Item item = new Item();
            item.title = obj.getString("title");
            item.content = obj.getString("content");
            mDataList.add(item);
        }
        mAdapter.notifyDataSetChanged();
    } catch (JSONException e) { e.printStackTrace(); }
}

參考教學

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved