推荐列表实现虚拟+无限循环

This commit is contained in:
2025-10-14 16:59:02 +08:00
parent a389733596
commit b40b02e2a2
4 changed files with 336 additions and 180 deletions
+1 -1
View File
@@ -396,7 +396,7 @@ export default class ResManager {
spttemp.frameUrl = url;
// 加载
assetManager.loadRemote<ImageAsset>(url, (err, res: ImageAsset) => {
logger.log("changeRemoteSpriteFrame方法加载远程图片: ", url);
//logger.log("changeRemoteSpriteFrame方法加载远程图片: ", url);
if (err) {
logger.log(err);
return;
+148 -111
View File
@@ -34,6 +34,8 @@ import proto from "db://assets/Scripts/proto/proto.pb.js";
import { MainController } from "../../core/MainController";
import { logger } from "db://assets/Scripts/Main/Common/Logger";
import { RecomandItem } from "../../uiitems/RecomandItem";
import HXZ_ScrollViewList from "db://assets/Scripts/Main/Common/ScrollViewList";
import ScrollViewListItem from "db://assets/Scripts/Main/Common/ScrollviewListItem";
const { ccclass, property } = _decorator;
@@ -54,7 +56,11 @@ export class ThemePanel extends li_BaseView {
cache: ThemeItem[] = [];
recItemCache: RecomandItem[] = [];
// 不再需要手动管理 recItemCache
// recItemCache: RecomandItem[] = [];
// 虚拟列表组件
private scrollViewList: HXZ_ScrollViewList = null;
// 子页面管理
@@ -76,6 +82,9 @@ export class ThemePanel extends li_BaseView {
private isLoadingMore: boolean = false;
private hasMoreData: boolean = true;
// 记录上次触发加载的 ID,避免重复触发
private lastLoadTriggerId: number = -1;
onLoadCT() {
Utils.parseNode(this.node, this._nodeTab);
@@ -93,6 +102,15 @@ export class ThemePanel extends li_BaseView {
if (this.recomandScroll) {
this.recomandScrollView =
this.recomandScroll.getComponentInChildren(ScrollView);
// 获取虚拟列表组件(需要在场景中手动添加 HXZ_ScrollViewList 组件)
this.scrollViewList =
this.recomandScroll.getComponentInChildren(HXZ_ScrollViewList);
if (!this.scrollViewList) {
logger.warn(
"[ThemePanel] recomandScroll 节点缺少 HXZ_ScrollViewList 组件,请在编辑器中添加"
);
}
}
this.registerListener();
@@ -100,6 +118,7 @@ export class ThemePanel extends li_BaseView {
this.itemInst.node.active = false;
this.recItemInst = this._nodeTab.recItem.getComponent(RecomandItem);
// 虚拟列表会自动管理模板节点的显隐,但保留兼容性代码
this.recItemInst.node.active = false;
this.themeContent = this._nodeTab.allThemecontent;
@@ -249,6 +268,38 @@ export class ThemePanel extends li_BaseView {
}
}
/**
* 虚拟列表渲染回调
* 该方法需要在 Cocos Creator 编辑器中配置到 HXZ_ScrollViewList 的 renderEvent
* @param itemNode 虚拟列表传入的节点
* @param index 数据索引
*/
onRenderRecommendItem(itemNode: Node, index: number): void {
const girlData = DataManager.I.getDataById<GirlData>(DataId.Girl);
const girlIDs = girlData.getRecommendListIds();
if (index < girlIDs.length) {
const girlId = girlIDs[index];
const item = itemNode.getComponent(RecomandItem);
if (!item) {
logger.error(
`[ThemePanel] 节点缺少 RecomandItem 组件,index: ${index}`
);
return;
}
// 确保节点已初始化
if (!item._initialized) {
item.init();
}
// 刷新数据
item.refresh(girlId);
itemNode.active = true;
}
}
/**
* 处理推荐数据
*/
@@ -277,59 +328,62 @@ export class ThemePanel extends li_BaseView {
/**
* 渲染推荐列表数据(首次渲染)
* 【已废弃】使用虚拟列表后,不再需要手动渲染,通过 numItems 触发自动渲染
*/
private renderRecommendData(): void {
if (this.recItemCache.length > 0) return;
// 重置分页状态
this.currentPage = 1;
this.hasMoreData = true;
this.isLoadingMore = false;
const girlData = DataManager.I.getDataById<GirlData>(DataId.Girl);
// 获取推荐列表的所有 ID
let girlIDs = girlData.getRecommendListIds();
// 遍历创建推荐项
for (let id of girlIDs) {
let newNode = instantiate(this.recItemInst.node);
let item = newNode.getComponent(RecomandItem);
item.init();
item.refresh(id);
newNode.active = true;
this.recItemCache.push(item);
this.recGirlContent.addChild(newNode);
}
// 检查首次加载的数据量,判断是否还有更多数据
if (girlIDs.length < this.pageLimit) {
this.hasMoreData = false;
}
logger.log(`[ThemePanel] 渲染推荐列表完成,共 ${girlIDs.length} 个推荐项`);
private renderRecommendData_DEPRECATED(): void {
// 该方法已被虚拟列表的自动渲染机制替代
// 保留此方法仅用于参考,实际不再调用
}
/**
* 滚动到底部回调(Cocos Creator 内置事件
* 滚动到底部回调(已废弃
* 该方法不再使用,改用 onRecommendScrolling() 中的滚动偏移量检测
* scroll-to-bottom 事件触发不稳定,改为在 scrolling 事件中检测距离底部的距离
*/
private onRecommendScrollToBottom(): void {
private onRecommendScrollToBottom_DEPRECATED(): void {
logger.log("[ThemePanel] 推荐列表滚动到底部");
this.loadMoreRecommendData();
}
/**
* 滚动中回调,用于检测接近底部
* 滚动中回调,基于虚拟列表 displayData 检测并触发分页加载
* 当显示到接近已加载数据末尾时(倒数第3个),自动加载下一页
*/
private onRecommendScrolling(): void {
if (!this.recomandScrollView) return;
if (!this.scrollViewList) return;
// 获取滚动进度(0-1
const scrollOffset = this.recomandScrollView.getScrollOffset();
const maxScrollOffset = this.recomandScrollView.getMaxScrollOffset();
// 获取虚拟列表的 displayData 和总数
const displayData = this.scrollViewList.displayData;
const numItems = this.scrollViewList.numItems;
// 当滚动到距离底部 100 像素以内时,开始加载
if (maxScrollOffset.y > 0 && scrollOffset.y >= maxScrollOffset.y - 100) {
// 检查数据有效性
if (!displayData || displayData.length === 0 || numItems === 0) return;
// 获取当前显示的最后一个 item 的 ID
const lastDisplayedId = displayData[displayData.length - 1].id;
// 调试日志(显示当前滚动状态)
const firstDisplayedId = displayData[0].id;
logger.log(
`[滚动] 显示范围: ID ${firstDisplayedId}-${lastDisplayedId}, 总数: ${numItems}, 已加载页: ${this.currentPage}`
);
// 触发条件:显示到倒数第 3 个 item 时开始加载下一页
// 例如:总数 10,显示到 ID=7 时触发(10-3=7
// 总数 20,显示到 ID=17 时触发(20-3=17
const threshold = numItems - 3;
if (lastDisplayedId >= threshold && lastDisplayedId > this.lastLoadTriggerId) {
logger.log(
`[ThemePanel] 接近末尾 (${lastDisplayedId}/${numItems}),触发加载第 ${
this.currentPage + 1
}`
);
// 记录本次触发的 ID,避免重复触发
this.lastLoadTriggerId = lastDisplayedId;
// 触发分页加载
this.loadMoreRecommendData();
}
}
@@ -376,12 +430,16 @@ export class ThemePanel extends li_BaseView {
logger.log("[ThemePanel] 已加载所有推荐数据");
}
// 渲染新增数据
this.renderMoreRecommendData(girls.length);
logger.log(
`[ThemePanel] 第 ${this.currentPage} 页加载完成,新增 ${girls.length}`
);
// 使用虚拟列表:更新总数量,自动触发渲染
if (this.scrollViewList) {
const allGirlIDs = girlData.getRecommendListIds();
this.scrollViewList.numItems = allGirlIDs.length;
logger.log(
`[ThemePanel] 第 ${this.currentPage} 页加载完成,新增 ${girls.length} 项,总计 ${allGirlIDs.length}`
);
} else {
logger.warn("[ThemePanel] scrollViewList 未初始化,无法更新列表");
}
} else {
logger.warn("[ThemePanel] 加载下一页推荐数据失败:", res);
// 加载失败,回退页码
@@ -398,31 +456,12 @@ export class ThemePanel extends li_BaseView {
/**
* 渲染新增的推荐数据
* 【已废弃】使用虚拟列表后,通过更新 numItems 自动触发渲染
* @param newCount 新增数据的数量
*/
private renderMoreRecommendData(newCount: number): void {
if (newCount <= 0) return;
const girlData = DataManager.I.getDataById<GirlData>(DataId.Girl);
const allGirlIDs = girlData.getRecommendListIds();
// 只渲染新增的部分(从末尾开始取 newCount 个)
const startIndex = allGirlIDs.length - newCount;
const newGirlIDs = allGirlIDs.slice(startIndex);
logger.log(`[ThemePanel] 开始渲染 ${newCount} 个新增推荐项`);
for (let id of newGirlIDs) {
let newNode = instantiate(this.recItemInst.node);
let item = newNode.getComponent(RecomandItem);
item.init();
item.refresh(id);
newNode.active = true;
this.recItemCache.push(item);
this.recGirlContent.addChild(newNode);
}
logger.log(`[ThemePanel] 新增推荐项渲染完成`);
private renderMoreRecommendData_DEPRECATED(newCount: number): void {
// 该方法已被虚拟列表的自动渲染机制替代
// 保留此方法仅用于参考,实际不再调用
}
/**
@@ -446,19 +485,18 @@ export class ThemePanel extends li_BaseView {
GButton.BandClick(this.recomandListBtn, this.openRecomandList, this);
GButton.BandClick(this.moreThemeBtn, this.openMoreTheme, this);
// 注册推荐列表滚动事件
if (this.recomandScrollView) {
this.recomandScrollView.node.on(
"scroll-to-bottom",
this.onRecommendScrollToBottom,
this
);
this.recomandScrollView.node.on(
"scrolling",
this.onRecommendScrolling,
this
);
}
// 注册推荐列表滚动事件(延迟到下一帧,确保虚拟列表已初始化)
this.scheduleOnce(() => {
if (this.scrollViewList) {
// 只监听 scrolling 事件,通过滚动偏移量检测是否接近底部
this.scrollViewList.node.on("scrolling", this.onRecommendScrolling, this);
logger.log("[ThemePanel] 虚拟列表滚动事件已绑定");
} else {
logger.warn(
"[ThemePanel] 无法绑定滚动事件,scrollViewList 未初始化"
);
}
}, 0.1);
Utils.addInnerEL(InnerMsgCode.LanguageChange, this, this.onLanguageChange);
Utils.addInnerEL(InnerMsgCode.BalanceChange, this, this.onBalanceChange);
@@ -477,8 +515,23 @@ export class ThemePanel extends li_BaseView {
this.themeScroll.active = false;
this.recomandScroll.active = true;
//todo:是否需要刷新数据
this.renderRecommendData();
// 使用虚拟列表:设置数据总量,自动触发渲染
if (this.scrollViewList) {
const girlData = DataManager.I.getDataById<GirlData>(DataId.Girl);
const girlIDs = girlData.getRecommendListIds();
// 重置分页状态(仅在首次打开时)
if (this.scrollViewList.numItems === 0) {
this.currentPage = 1;
this.hasMoreData = true;
this.isLoadingMore = false;
}
this.scrollViewList.numItems = girlIDs.length;
logger.log(`[ThemePanel] 打开推荐列表,共 ${girlIDs.length}`);
} else {
logger.warn("[ThemePanel] scrollViewList 未初始化");
}
this.updateTagState(true);
}
@@ -562,27 +615,19 @@ export class ThemePanel extends li_BaseView {
this.cache = [];
}
// 清理推荐项缓存
if (this.recItemCache && this.recItemCache.length > 0) {
logger.log(
`[ThemePanel] 清理 ${this.recItemCache.length} 个推荐项缓存节点`
);
for (let i = this.recItemCache.length - 1; i >= 0; i--) {
if (
this.recItemCache[i] &&
this.recItemCache[i].node &&
this.recItemCache[i].node.isValid
) {
this.recItemCache[i].node.destroy();
}
}
this.recItemCache = [];
// 虚拟列表自动管理对象池,只需重置数量
if (this.scrollViewList) {
this.scrollViewList.numItems = 0;
logger.log("[ThemePanel] 重置虚拟列表项数量");
}
// 重置推荐列表分页状态
this.currentPage = 1;
this.hasMoreData = true;
this.isLoadingMore = false;
// 重置触发记录
this.lastLoadTriggerId = -1;
}
/**
@@ -617,18 +662,10 @@ export class ThemePanel extends li_BaseView {
this.isLoading = false;
this.loadingPromise = null;
// 移除推荐列表滚动事件监听
if (this.recomandScrollView) {
this.recomandScrollView.node.off(
"scroll-to-bottom",
this.onRecommendScrollToBottom,
this
);
this.recomandScrollView.node.off(
"scrolling",
this.onRecommendScrolling,
this
);
// 移除虚拟列表滚动事件监听
if (this.scrollViewList) {
this.scrollViewList.node.off("scrolling", this.onRecommendScrolling, this);
logger.log("[ThemePanel] 虚拟列表滚动事件已移除");
}
// 移除事件监听器(修复回调函数引用问题)
+27 -6
View File
@@ -29,7 +29,15 @@ export class RecomandItem extends Component {
private id: number;
// 标记是否已初始化(用于虚拟列表复用)
public _initialized: boolean = false;
// 兼容原有调用方式的 init 方法
init() {
if (this._initialized) {
return;
}
Utils.parseNode(this.node, this._nodeTab);
this.recPic = this._nodeTab.recPic.getComponent(Sprite);
@@ -45,6 +53,14 @@ export class RecomandItem extends Component {
this.chatBtn = this._nodeTab.chatBtn;
GButton.BandClick(this.chatBtn, this.chatToHer, this);
GButton.BandClick(this._nodeTab.detailBtn, this.gotoDetail, this);
this._initialized = true;
}
// 节点回收到对象池时调用,重置状态
reset(): void {
this.id = -1;
this.node.active = false;
}
refresh(girlId: number) {
@@ -72,7 +88,7 @@ export class RecomandItem extends Component {
});
const star = girlData.getStar(category.toString(), this.id);
logger.log("好感度:" + star);
//logger.log("好感度:" + star);
for (let i = 0; i < this.hearts.length; i++) {
const element = this.hearts[i];
if (star > i) {
@@ -100,11 +116,16 @@ export class RecomandItem extends Component {
const currentPanel = NavigationManager.Instance.getCurrentActivePanelNode();
if (currentPanel) {
const chatData = { girlId: this.id, base: currentPanel };
NavigationManager.Instance.openSubPanel("ChatPanel", currentPanel, chatData, {
openAnimation: PageTransitionType.SLIDE_LEFT,
closeAnimation: PageTransitionType.SLIDE_RIGHT,
hideBasePanel: true,
});
NavigationManager.Instance.openSubPanel(
"ChatPanel",
currentPanel,
chatData,
{
openAnimation: PageTransitionType.SLIDE_LEFT,
closeAnimation: PageTransitionType.SLIDE_RIGHT,
hideBasePanel: true,
}
);
} else {
logger.warn("[RecomandItem] 无法获取当前激活的主页面");
}