配置了 PullToRefreshGridView,寬高、列數、間距均已設置,但數據不顯示。
<com.handmark.pulltorefresh.library.PullToRefreshGridView
android:id="@+id/select_history_time_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="8dp"
android:listSelector="#00000000"
android:numColumns="2"
android:scrollbars="none"
android:verticalSpacing="10dp" />
// 在設置 Adapter 前打印日誌
List<YourBean> dataList = getData();
Log.d("GridViewDebug", "數據源大小: " + (dataList != null ? dataList.size() : "null"));
if (dataList == null || dataList.isEmpty()) {
// 處理空數據情況:顯示佔位圖或提示文本
return;
}
PullToRefreshGridView pullRefreshGridView = findViewById(R.id.select_history_time_grid);
// 關鍵:必須獲取內部的 GridView
GridView gridView = pullRefreshGridView.getRefreshableView();
YourAdapter adapter = new YourAdapter(this, dataList);
gridView.setAdapter(adapter); // 而不是 pullRefreshGridView.setAdapter()
public class YourAdapter extends BaseAdapter {
@Override
public int getCount() {
return dataList.size(); // 確保返回正確數量
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 確保正確 inflate 佈局並綁定數據
// 建議使用 ViewHolder 模式優化性能
}
}
如果 PullToRefreshGridView 在 ScrollView 或 NestedScrollView 內,會導致高度測量異常。解決方案:
ListView/GridView 專用的 PullToRefresh 容器GridView 重寫 onMeasure:public class MyGridView extends GridView {
public MyGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
數據加載完成後,必須調用:
pullRefreshGridView.onRefreshComplete();
// 如果是加載更多
pullRefreshGridView.onRefreshComplete();
// 並確保 Adapter 數據更新後 notifyDataSetChanged()
adapter.notifyDataSetChanged();
getRefreshableView() 獲取真實 GridView?getCount() 是否返回 > 0?getView() 是否正確返回 View?notifyDataSetChanged()?onRefreshComplete() 重置刷新狀態?90% 的「不顯示數據」問題源於 數據源為空 或 未正確獲取內部 GridView 設置 Adapter。按清單逐項排查即可定位。