WanAndroid(鸿蒙版)开发的第二篇

2024-03-14 02:28

本文主要是介绍WanAndroid(鸿蒙版)开发的第二篇,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

DevEco Studio版本:4.0.0.600

WanAndroid的API链接:玩Android 开放API-玩Android - wanandroid.com

1、 WanAndroid(鸿蒙版)开发的第一篇

3、WanAndroid(鸿蒙版)开发的第三篇

其他一些参考点,请参考上面的WanAndroid开发第一篇

效果

首页实现

整体布局分为头部的Banner和底部的列表List,知道了整体的机构我们就来进行UI布局

1、Banner实现

参考华为官方  OpenHarmony Swiper

详细代码:

import router from '@ohos.router';
import { BannerItemBean } from '../bean/BannerItemBean';
import { HttpManager, RequestMethod } from '@app/BaseLibrary';
import LogUtils from '@app/BaseLibrary/src/main/ets/utils/LogUtils';
import { BannerBean } from '../bean/BannerBean';const TAG = 'Banner--- ';@Component
export struct Banner {@State bannerData: Array<BannerItemBean> = [];private swiperController: SwiperController = new SwiperController();@State isVisibility: boolean = trueprivate onDataFinish: () => void //数据加载完成回调aboutToAppear() {this.getBannerData()}private getBannerData() {HttpManager.getInstance().request<BannerBean>({method: RequestMethod.GET,header: { "Content-Type": "application/json" },url: 'https://www.wanandroid.com/banner/json', //wanAndroid的API:Banner}).then((result: BannerBean) => {LogUtils.info(TAG, "result: " + JSON.stringify(result))if (result.errorCode == 0) {this.isVisibility = truethis.bannerData = result.data} else {this.isVisibility = false}this.onDataFinish()}).catch((error) => {LogUtils.info(TAG, "error: " + JSON.stringify(error))this.isVisibility = falsethis.onDataFinish()})}build() {Swiper(this.swiperController) {ForEach(this.bannerData, (banner: BannerItemBean) => {Image(banner.imagePath).borderRadius(16).onClick(() => {router.pushUrl({url: 'pages/WebPage',params: {title: banner.title,uriLink: banner.url,isShowCollect: false,}}, router.RouterMode.Single)})}, (banner: BannerItemBean) => banner.url)}.margin({ top: 10 }).autoPlay(true).interval(1500).visibility(this.isVisibility ? Visibility.Visible : Visibility.None).width('100%').height(150)}
}

2、List列表实现

因为是带上拉加载和下拉刷新,参考我之前文章:鸿蒙自定义刷新组件使用_harmoneyos 自定义刷新

详细代码:

import {BaseResponseBean,Constants,HtmlUtils,HttpManager,RefreshController,RefreshListView,RequestMethod
} from '@app/BaseLibrary';
import LogUtils from '@app/BaseLibrary/src/main/ets/utils/LogUtils';
import { HomeListItemBean } from '../bean/HomeListItemBean';
import { HomeListBean } from '../bean/HomeListBean';
import router from '@ohos.router';
import promptAction from '@ohos.promptAction';const TAG = 'HomeList--- ';@Component
export struct HomeList {@State controller: RefreshController = new RefreshController()@State homeListData: Array<HomeListItemBean> = [];@State pageNum: number = 0@State isRefresh: boolean = trueprivate onDataFinish: () => void //数据加载完成回调@State userName: string = ''@State token_pass: string = ''@State listCollectState: Array<boolean> = [] //用于存储收藏状态aboutToAppear() {if (AppStorage.Has(Constants.APPSTORAGE_USERNAME)) {this.userName = AppStorage.Get(Constants.APPSTORAGE_USERNAME) as string}if (AppStorage.Has(Constants.APPSTORAGE_TOKEN_PASS)) {this.token_pass = AppStorage.Get(Constants.APPSTORAGE_TOKEN_PASS) as string}this.getHomeListData()}/*** 获取列表数据*/private getHomeListData() {HttpManager.getInstance().request<HomeListBean>({method: RequestMethod.GET,header: {"Content-Type": "application/json","Cookie": `loginUserName=${this.userName}; token_pass=${this.token_pass}`},url: `https://www.wanandroid.com/article/list/${this.pageNum}/json` //wanAndroid的API:Banner}).then((result: HomeListBean) => {LogUtils.info(TAG, "result: " + JSON.stringify(result))if (this.isRefresh) {this.controller.finishRefresh()} else {this.controller.finishLoadMore()}if (result.errorCode == 0) {if (this.isRefresh) {this.homeListData = result.data.datasfor (let i = 0; i < this.homeListData.length; i++) {this.listCollectState[i] = this.homeListData[i].collect}} else {this.homeListData = this.homeListData.concat(result.data.datas)}}this.onDataFinish()}).catch((error) => {LogUtils.info(TAG, "error: " + JSON.stringify(error))if (this.isRefresh) {this.controller.finishRefresh()} else {this.controller.finishLoadMore()}this.onDataFinish()})}@BuilderitemLayout(item: HomeListItemBean, index: number) {RelativeContainer() {//作者或分享人Text(item.author.length > 0 ? "作者:" + item.author : "分享人:" + item.shareUser).fontColor('#666666').fontSize(14).id("textAuthor").alignRules({top: { anchor: '__container__', align: VerticalAlign.Top },left: { anchor: '__container__', align: HorizontalAlign.Start }})Text(item.superChapterName + '/' + item.chapterName).fontColor('#1296db').fontSize(14).id("textChapterName").alignRules({top: { anchor: '__container__', align: VerticalAlign.Top },right: { anchor: '__container__', align: HorizontalAlign.End }})//标题Text(HtmlUtils.formatStr(item.title)).fontColor('#333333').fontWeight(FontWeight.Bold).maxLines(2).textOverflow({overflow: TextOverflow.Ellipsis}).fontSize(20).margin({ top: 10 }).id("textTitle").alignRules({top: { anchor: 'textAuthor', align: VerticalAlign.Bottom },left: { anchor: '__container__', align: HorizontalAlign.Start }})//更新时间Text("时间:" + item.niceDate).fontColor('#666666').fontSize(14).id("textNiceDate").alignRules({bottom: { anchor: '__container__', align: VerticalAlign.Bottom },left: { anchor: '__container__', align: HorizontalAlign.Start }})//收藏状态Image(this.listCollectState[index] ? $r('app.media.ic_select_collect') : $r('app.media.ic_normal_collect')).width(26).height(26).id('imageCollect').alignRules({bottom: { anchor: '__container__', align: VerticalAlign.Bottom },right: { anchor: '__container__', align: HorizontalAlign.End }}).onClick(() => {this.setCollectData(item.id, index)})}.width('100%').height(120).padding(10).margin({ left: 10, right: 10, top: 6, bottom: 6 }).borderRadius(10).backgroundColor(Color.White)}build() {RefreshListView({list: this.homeListData,controller: this.controller,isEnableLog: true,refreshLayout: (item: HomeListItemBean, index: number): void => this.itemLayout(item, index),onItemClick: (item: HomeListItemBean, index: number) => {LogUtils.info(TAG, "点击了:index: " + index + " item: " + item)router.pushUrl({url: 'pages/WebPage',params: {title: item.title,uriLink: item.link,isShowCollect: true,isCollect: this.listCollectState[index]}}, router.RouterMode.Single)},onRefresh: () => {//下拉刷新this.isRefresh = truethis.pageNum = 0this.getHomeListData()},onLoadMore: () => {//上拉加载this.isRefresh = falsethis.pageNum++this.getHomeListData()}})}/*** 设置收藏和取消收藏状态* @param id  文章id* @param index  数据角标*/private setCollectData(id: number, index: number) {let collect = this.listCollectState[index]let urlLink = collect ? `https://www.wanandroid.com/lg/uncollect_originId/${id}/json` : `https://www.wanandroid.com/lg/collect/${id}/json` //取消收藏和收藏接口HttpManager.getInstance().request<BaseResponseBean>({method: RequestMethod.POST,header: {"Content-Type": "application/json","Cookie": `loginUserName=${this.userName}; token_pass=${this.token_pass}`},url: urlLink //wanAndroid的API:收藏和取消收藏}).then((result: BaseResponseBean) => {LogUtils.info(TAG, "收藏  result: " + JSON.stringify(result))if (result.errorCode == 0) {this.listCollectState[index] = !this.listCollectState[index]promptAction.showToast({ message: collect ? "取消收藏成功" : "收藏成功" })} else {promptAction.showToast({ message: result.errorMsg })}}).catch((error) => {LogUtils.info(TAG, "收藏  error: " + JSON.stringify(error))})}
}

注意点:就是在获取List数据时,通过WanAndroid的API知道要想获取收藏状态需要传入用户登录时的Cookie,但是鸿蒙没有像Android那样的Cookie处理,只能通过在登录的时候获取loginUserName和token_pass然后在请求时将这两个参数添加到请求头中,实现如下图:

这两个参数获取参考第一篇的文章。

3、将两个视图整合

详细代码:

import { Banner } from './widget/Banner';
import { HomeList } from './widget/HomeList';
import { LoadingDialog } from '@app/BaseLibrary';
import LogUtils from '@app/BaseLibrary/src/main/ets/utils/LogUtils';@Component
export struct HomePage {@State bannerLoadDataStatus: boolean = false@State HomeListLoadDataStatus: boolean = falseaboutToAppear() {//弹窗控制器,显示this.dialogController.open()}private dialogController = new CustomDialogController({builder: LoadingDialog(),customStyle: true,alignment: DialogAlignment.Center, // 可设置dialog的对齐方式,设定显示在底部或中间等,默认为底部显示})build() {Column() {Banner({ onDataFinish: () => {this.bannerLoadDataStatus = trueLogUtils.info("33333333333 Banner  bannerLoadDataStatus: " + this.bannerLoadDataStatus + "  HomeListLoadDataStatus: " + this.HomeListLoadDataStatus)if (this.bannerLoadDataStatus && this.HomeListLoadDataStatus) {this.dialogController.close()}} })HomeList({ onDataFinish: () => {this.HomeListLoadDataStatus = trueLogUtils.info("33333333333 HomeList  bannerLoadDataStatus: " + this.bannerLoadDataStatus + "  HomeListLoadDataStatus: " + this.HomeListLoadDataStatus)if (this.bannerLoadDataStatus && this.HomeListLoadDataStatus) {this.dialogController.close()}} }).flexShrink(1).margin({ top: 10 })}.visibility(this.bannerLoadDataStatus && this.HomeListLoadDataStatus ? Visibility.Visible : Visibility.Hidden).width('100%').height('100%')}
}

源代码地址:WanAndroid_Harmony: WanAndroid的鸿蒙版本

这篇关于WanAndroid(鸿蒙版)开发的第二篇的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/806938

相关文章

基于Python开发一个有趣的工作时长计算器

《基于Python开发一个有趣的工作时长计算器》随着远程办公和弹性工作制的兴起,个人及团队对于工作时长的准确统计需求日益增长,本文将使用Python和PyQt5打造一个工作时长计算器,感兴趣的小伙伴可... 目录概述功能介绍界面展示php软件使用步骤说明代码详解1.窗口初始化与布局2.工作时长计算核心逻辑3

python web 开发之Flask中间件与请求处理钩子的最佳实践

《pythonweb开发之Flask中间件与请求处理钩子的最佳实践》Flask作为轻量级Web框架,提供了灵活的请求处理机制,中间件和请求钩子允许开发者在请求处理的不同阶段插入自定义逻辑,实现诸如... 目录Flask中间件与请求处理钩子完全指南1. 引言2. 请求处理生命周期概述3. 请求钩子详解3.1

如何基于Python开发一个微信自动化工具

《如何基于Python开发一个微信自动化工具》在当今数字化办公场景中,自动化工具已成为提升工作效率的利器,本文将深入剖析一个基于Python的微信自动化工具开发全过程,有需要的小伙伴可以了解下... 目录概述功能全景1. 核心功能模块2. 特色功能效果展示1. 主界面概览2. 定时任务配置3. 操作日志演示

JavaScript实战:智能密码生成器开发指南

本文通过JavaScript实战开发智能密码生成器,详解如何运用crypto.getRandomValues实现加密级随机密码生成,包含多字符组合、安全强度可视化、易混淆字符排除等企业级功能。学习密码强度检测算法与信息熵计算原理,获取可直接嵌入项目的完整代码,提升Web应用的安全开发能力 目录

一文教你如何解决Python开发总是import出错的问题

《一文教你如何解决Python开发总是import出错的问题》经常朋友碰到Python开发的过程中import包报错的问题,所以本文将和大家介绍一下可编辑安装(EditableInstall)模式,可... 目录摘要1. 可编辑安装(Editable Install)模式到底在解决什么问题?2. 原理3.

Python+PyQt5开发一个Windows电脑启动项管理神器

《Python+PyQt5开发一个Windows电脑启动项管理神器》:本文主要介绍如何使用PyQt5开发一款颜值与功能并存的Windows启动项管理工具,不仅能查看/删除现有启动项,还能智能添加新... 目录开篇:为什么我们需要启动项管理工具功能全景图核心技术解析1. Windows注册表操作2. 启动文件

使用Python开发Markdown兼容公式格式转换工具

《使用Python开发Markdown兼容公式格式转换工具》在技术写作中我们经常遇到公式格式问题,例如MathML无法显示,LaTeX格式错乱等,所以本文我们将使用Python开发Markdown兼容... 目录一、工具背景二、环境配置(Windows 10/11)1. 创建conda环境2. 获取XSLT

Android开发环境配置避坑指南

《Android开发环境配置避坑指南》本文主要介绍了Android开发环境配置过程中遇到的问题及解决方案,包括VPN注意事项、工具版本统一、Gerrit邮箱配置、Git拉取和提交代码、MergevsR... 目录网络环境:VPN 注意事项工具版本统一:android Studio & JDKGerrit的邮

Python开发文字版随机事件游戏的项目实例

《Python开发文字版随机事件游戏的项目实例》随机事件游戏是一种通过生成不可预测的事件来增强游戏体验的类型,在这篇博文中,我们将使用Python开发一款文字版随机事件游戏,通过这个项目,读者不仅能够... 目录项目概述2.1 游戏概念2.2 游戏特色2.3 目标玩家群体技术选择与环境准备3.1 开发环境3

Go语言开发实现查询IP信息的MCP服务器

《Go语言开发实现查询IP信息的MCP服务器》随着MCP的快速普及和广泛应用,MCP服务器也层出不穷,本文将详细介绍如何在Go语言中使用go-mcp库来开发一个查询IP信息的MCP... 目录前言mcp-ip-geo 服务器目录结构说明查询 IP 信息功能实现工具实现工具管理查询单个 IP 信息工具的实现服