当前位置:

首页 > 系统应用 > 官方总结鸿蒙应用开发常见问题与实现方法典型案例

官方总结鸿蒙应用开发常见问题与实现方法典型案例

1自定义Dialog的布局1.1 问题描述如何实现自定义的Dialog?1.2 实现方法添加自定义Dialog代码CommonDialog commonDialog = new CommonDialog(this);Component component = LayoutScatter.getIns

本文目录
    1自定义Dialog的布局

    1.1 问题描述

    如何实现自定义的Dialog?

    1.2 实现方法

    添加自定义Dialog代码

    CommonDialog commonDialog = new   CommonDialog(this);

    Component component = LayoutScatter.getInstance(getContext())

    .parse(ResourceTable.Layout_dialog_custom_layout, null, true);

    commonDialog.setSize(800, 500);

    commonDialog.setContentCustomComponent(component);

    commonDialog.show();

    自定义Dialog的布局文件



    ohos:width="match_parent"
    ohos:height="match_content"
    ohos:padding="10vp"
    ohos:background_element="@graphic:grey"
    ohos:orientation="vertical">

    ohos:width="match_parent"
    ohos:height="match_content"
    ohos:text="Dialog标题"
    ohos:text_color="$color:Black"
    ohos:text_style="bold"
    ohos:text_size="40fp"/>

    ohos:width="match_parent"
    ohos:height="match_parent"
    ohos:text="自定义Dialog内容"
    ohos:text_color="$color:Black"
    ohos:text_style="bold"
    ohos:weight="1"
    ohos:text_alignment="vertical_center"
    ohos:top_margin="30vp"
    ohos:bottom_margin="30vp"
    ohos:left_margin="10vp"
    ohos:right_margin="10vp"
    ohos:text_size="30fp"/>

    ohos:height="match_content"
    ohos:width="match_parent"
    ohos:orientation="horizontal">

    ohos:width="match_parent"
    ohos:text="取消"
    ohos:text_size="30fp"
    ohos:padding="10vp"
    ohos:text_color="$color:White"
    ohos:weight="1"
    ohos:margin="10vp"
    ohos:background_element="$graphic:yellow"
    ohos:height="match_content"/>

    ohos:width="match_parent"
    ohos:text="确定"
    ohos:text_size="30fp"
    ohos:weight="1"
    ohos:padding="10vp"
    ohos:text_color="$color:White"
    ohos:margin="10vp"
    ohos:background_element="$graphic:green"
    ohos:height="match_content"/>

    1.3 实际效果

    2 设置控件背景颜色

    2.1 问题描述

    在xml布局中,若设置控件的ohos:background_element="$color:yellow",是无法生效的。目前,背景颜色仅支持以$graphic方式进行设置,而不支持以$color方式设置。

    2.2 实现方法

    方式1:xml中设置控件背景颜色使用$graphic

          ohos:width="match_parent"
    ohos:text="控件按钮"
    ohos:text_size="30fp"
    ohos:padding="10vp"
    ohos:text_color="$color:White"
    ohos:background_element="$graphic:yellow"
    ohos:height="match_content"/>

    资源文件graphic中yellow.xml代码如下:


    ohos:shape="rectangle">
    ohos:color="#fff9a825"/>

    方式2:纯代码设置控件颜色

    DirectionalLayout.LayoutConfig   config = new   DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_CONTENT,   DirectionalLayout.LayoutConfig.MATCH_CONTENT);

    config.setMargins(30, 10, 10, 10);
    ShapeElement element = new ShapeElement();
    element.setRgbColor(new RgbColor(255, 111, 0));
    Text text = new Text(this);
    text.setText("xml添加背景");
    text.setTextColor(new Color(0xFFFFFFFF));
    text.setTextSize(40);
    text.setPadding(30, 20, 30, 20);
    text.setTextAlignment(TextAlignment.CENTER);
    text.setBackground(element);
    text.setLayoutConfig(config);

    2.3 实际效果

    3 ScrollView嵌套DirectionalLayout进行滚动

    3.1 问题描述

    ScrollView嵌套DirectionalLayout如何进行滚动?

    3.2 实现方法

    1. 使用xml布局,需要将ScrollView的高度设置成“match_parent”,ScrollView子布局的高度设置成“match_content”


    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:width="match_parent"
    ohos:height="match_parent"
    ohos:orientation="vertical">

    ohos:width="match_parent"
    ohos:height="match_content"
    ohos:orientation="vertical">
    ...

    1. 使用代码添加,则需要给ScrollView和子布局设置LayoutConfig
    ComponentContainer.LayoutConfig   scrollConfig = new   ComponentContainer.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_PARENT,   DirectionalLayout.LayoutConfig.MATCH_PARENT);

    scrollView.setLayoutConfig(scrollConfig);

    DirectionalLayout.LayoutConfig config = new DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_PARENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);

    myLayout.setLayoutConfig(config);

    ...

    scrollView.addComponent(myLayout);

    super.setUIContent(scrollView);

    3.3 实际效果

    4 加载和显示网络图片

    4.1 问题描述

    如何实现加载和显示网络图片?

    4.2 实现方法

    1. 在config.json中添加网络权限
    {
    "module": {
    "reqPermissions": [
    {
    "name": "ohos.permission.INTERNET"
    }
    ]
    }
    }
    1. 获取并设置网络图片
    String   urlImage = "https://www.harmonyos.com/resource/image/community/20201009-164134eSpace.jpg";

    HttpURLConnection connection = null;

    try {
    URL url = new URL(urlImage);
    URLConnection urlConnection = url.openConnection();
    if (urlConnection instanceof HttpURLConnection) {
    connection = (HttpURLConnection) urlConnection;
    }
    if (connection != null) {
    connection.connect();
    // 之后可进行url的其他操作
    // 得到服务器返回过来的流对象
    InputStream inputStream = urlConnection.getInputStream();
    ImageSource imageSource = ImageSource.create(inputStream, new ImageSource.SourceOptions());
    ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
    decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
    // 普通解码叠加旋转、缩放、裁剪
    PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
    // 普通解码
    getUITaskDispatcher().syncDispatch(() -> {
    Image image = new Image(HttpImageSlice.this);
    DirectionalLayout.LayoutConfig config = new DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
    config.setMargins(10, 10, 10, 10);
    image.setLayoutConfig(config);
    image.setPixelMap(pixelMap);
    myLayout.addComponent(image);
    pixelMap.release();
    });
    }

    } catch (Exception e) {
    e.printStackTrace();
    }

    4.3 实际效果

    5 ListContainer列表组件的使用

    5.1 问题描述

    ListContainer列表组件如何使用?

    5.2 实现方法

    在xml文件中声明组件


    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:width="match_parent"
    ohos:height="match_parent"
    ohos:orientation="vertical">

    ohos:id="$+id:list_container"
    ohos:orientation="vertical"
    ohos:width="match_parent"
    ohos:height="match_parent"/>

    获取 ListContainer 组件,并设置itemProvider

    private void initView() {
    mListContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
    ListItemProvider listItemProvider = new ListItemProvider();
    mListContainer.setItemProvider(listItemProvider);
    }

    自定义 ListItemProvider 继承 RecycleItemProvider

    class ListItemProvider extends RecycleItemProvider {
    @Override
    public int getCount() {
    return data.size();
    }
    @Override
    public long getItemId(int i) {
    return 0;
    }
    @Override
    public Component getComponent(int position, Component convertView, ComponentContainer componentContainer) {
    Component component = LayoutScatter.getInstance(getContext())
    .parse(ResourceTable.Layout_layout_container_item, null, false);
    if (!(component instanceof ComponentContainer)) {
    return null;
    }
    ComponentContainer rootLayout = (ComponentContainer) component;
    Text rightText = (Text) rootLayout.findComponentById(ResourceTable.Id_content);
    rightText.setText(data.get(position));
    return component;
    }
    }

    5.3 实际效果

    6 读取资源文件

    6.1 问题描述

    如何读取应用的资源文件?

    6.2 实现方法

    1. 对于图片文件,建议放到base/media目录下,Image组件可以直接设置,方法如下。
    Image image = (Image) findComponentById(ResourceTable.Id_component_image);
    image.setPixelMap(ResourceTable.Media_huawei);
    1. 对于rawfile文件的读写,请参考下面的方法:
    ohos.global.resource.ResourceManager resourceManager = getApplicationContext().getResourceManager();
    ohos.global.resource.RawFileEntry rawFileEntry = resourceManager.getRawFileEntry("resources/rawfile/test.png");
    RawFileDescriptor rawFileDescriptor = rawFileEntry.openRawFileDescriptor();
    // 或者
    Resource resource = rawFileEntry.openRawFile();

    6.3 实际效果

    7 JS方法获取位置信息

    7.1 问题描述

    使用JS开发时,如何获取位置信息?

    7.2 实现方法

    1. 导入获取位置模块,并调用getLocation方法获取位置信息
    import geolocation from '@system.geolocation';
    export default {
    data: {
    longitude: 0.0,
    latitude: 0.0
    },
    onInit() {
    this.getLocation();
    },
    getLocation() {
    var temp = this;
    geolocation.getLocation({
    success: function(data) {
    console.info("get location success, longitude: " + data.longitude +", latitude: " + data.latitude);
    temp.longitude = data.longitude
    temp.latitude = data.latitude;
    },
    fail: function(data, code) {
    console.error("get location failed, code: " + code + ", data: " + data);
    },
    complete: function() {
    console.info("get location complete");
    }
    });
    }
    }
    1. 在config.json中增加获取位置信息的权限
    "reqPermissions": [
    {
    "name": "ohos.permission.LOCATION"
    }
    ],

    7.3 实际效果

    8 禁用手表中系统的左右滑动

    8.1 问题描述

    开发一个应用支持左右滑动的操作,但是在模拟器中右滑时,默认跳转到系统页面,并退出应用,如何禁用系统右滑?

    8.2 实现方法

    覆盖MainAbility中的onTouchEvent方法,实现如下

    @Override
    protected boolean onTouchEvent(TouchEvent event) {
    super.onTouchEvent(event);
    return true;
    }

    8.3 实际效果

    9 Text控件中文字换行

    9.1 问题描述

    Text控件中文字目前不支持n换行,如何进行换行?

    9.2 实现方法

    可以使用系统自动换行,保持两行文字长度一致,实现如下


    ohos:width="match_parent"
    ohos:height="match_parent"
    ohos:orientation="vertical">
    ohos:id="$+id:text"
    ohos:width="150vp"
    ohos:height="match_content"
    ohos:multiple_lines="true"
    ohos:max_text_lines="2"
    ohos:auto_font_size="true"
    ohos:text="目前车辆尊享服务已过期, 车主续费后才可继续使用"/>

    9.3 实际效果

    10 在一个布局xml中引入其他xml布局文件

    10.1 问题描述

    定义了一个公共的XML布局文件,如何在其他XML布局文件中引用这个公共的XML布局文件?

    10.2 实现方法

    可以通过include标签引用其他的XML布局文件,示例如下:


    ohos:layout="$layout:include_layout"
    ohos:width="match_parent"
    ohos:height="match_content"/>

    10.3 实际效果

    NA

    11 自定义Swtich控件的颜色

    11.1 问题描述

    如何自定义Swtich控件的开关两个状态下的按钮颜色?

    11.2 实现方法

    需在资源文件graphic文件下,分别创建bg_element.xml和fg_element.xml,其中bg_element.xml文件的具体内容如下



    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">

    ohos:radius="30"/>
    ohos:color="#424242"/>

    fg_element.xml文件内容如下



    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="oval">
    ohos:color="#D81B60"/>

    代码实现自定义颜色:

    private void setupSwitch() {

    mSwitch = (Switch) findComponentById(ResourceTable.Id_switch_custom);

    Element elementBackground = ElementScatter.getInstance(this).parse(ResourceTable.Graphic_bg_element);

    mSwitch.setTrackElement(elementBackground);

    Element elementThumb = ElementScatter.getInstance(this).parse(ResourceTable.Graphic_fg_element);

    mSwitch.setThumbElement(elementThumb);

    mSwitch.setClickedListener(new Component.ClickedListener() {

    @Override

    public void onClick(Component component) {

    Log.i("switch: " + mSwitch.isChecked());

    }

    });

    }

    11.3 实际效果

    12 视频播放

    12.1 问题描述

    如何播放本地视频文件和网络视频?

    12.2 实现方法

    创建布局文件video_player_layout.xml,内容如下



    ohos:id="$+id:video_player_dl"
    ohos:width="match_parent"
    ohos:height="match_parent"
    ohos:orientation="vertical">

    定义下面的变量,内容如下:

    private static Player mPlayer;
    private SurfaceProvider mSurfaceProvider;
    private DependentLayout mLayout;

    实现SurfaceOps.Callback接口,代码如下:

    class VideoSurfaceCallback implements SurfaceOps.Callback {
    @Override
    public void surfaceCreated(SurfaceOps surfaceOps) {
    Log.i("surfaceCreated() called.");
    if (mSurfaceProvider.getSurfaceOps().isPresent()) {
    Surface surface = mSurfaceProvider.getSurfaceOps().get().getSurface();
    playUrl(surface);
    }
    }
    @Override
    public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) {
    Log.i("surfaceChanged() called.");
    }
    @Override
    public void surfaceDestroyed(SurfaceOps surfaceOps) {
    Log.i("surfaceDestroyed() called.");
    }
    }

    实现Player.IplayerCallback接口,代码如下:

    private class VideoPlayerCallback implements Player.IPlayerCallback {
    @Override
    public void onPrepared() {
    Log.i("onPrepared");
    }
    @Override
    public void onMessage(int i, int i1) {
    Log.i("onMessage");
    }
    @Override
    public void onError(int i, int i1) {
    Log.i("onError: i=" + i + ", i1=" + i1);
    }
    @Override
    public void onResolutionChanged(int i, int i1) {
    Log.i("onResolutionChanged");
    }
    @Override
    public void onPlayBackComplete() {
    Log.i("onPlayBackComplete");
    if (mPlayer != null) {
    mPlayer.stop();
    mPlayer = null;
    }
    }
    @Override
    public void onRewindToComplete() {
    Log.i("onRewindToComplete");
    }
    @Override
    public void onBufferingChange(int i) {
    Log.i("onBufferingChange");
    }
    @Override
    public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {
    Log.i("onNewTimedMetaData");
    }
    @Override
    public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {
    Log.i("onMediaTimeIncontinuity");
    }
    }

    实现播放本地文件的方法,其中test.mp4文件放到资源文件目录下,内容如下:

    private void playLocalFile(Surface surface) {
    try {
    RawFileDescriptor filDescriptor = getResourceManager().getRawFileEntry("resources/rawfile/test.mp4").openRawFileDescriptor();
    Source source = new Source(filDescriptor.getFileDescriptor(),filDescriptor.getStartPosition(),filDescriptor.getFileSize());
    mPlayer.setSource(source);
    mPlayer.setVideoSurface(surface);
    mPlayer.setPlayerCallback(new VideoPlayerCallback());
    mPlayer.prepare();
    mSurfaceProvider.setTop(0);
    mPlayer.play();
    } catch (Exception e) {
    Log.e("playUrl Exception:" + e.getMessage());
    }
    }

    实现播放网络URL的方法,其中video url为视频资源URL,内容如下:

    private void playUrl(Surface surface) {

    try {
    Source source = new Source("video url");
    mPlayer.setSource(source);
    mPlayer.setVideoSurface(surface);
    mPlayer.setPlayerCallback(new VideoPlayerCallback());
    mPlayer.prepare();
    mSurfaceProvider.setTop(0);
    mPlayer.play();
    } catch (Exception e) {
    Log.e("playUrl Exception:" + e.getMessage());
    }
    }

    播放网络视频,需要申请网络使用权限,在config.json中增加如下内容:

    "reqPermissions": [
    {
    "name": "ohos.permission.INTERNET"
    },
    ]

    12.3 实际效果

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    系统应用
    相关文章 更多
    AO3官网镜像链接一键跳转-手机入口快速访问
    AO3官网镜像链接一键跳转-手机入口快速访问

    AO3官网可通过https://www.ao3cn.cc//直接访问,支持手机和桌面端,页面适配移动端,操作流畅,支持书签、收藏、订阅及作品导出等功能,内容涵盖全球同人创作,分类细致,互动性强。

    AO3中文版官网与使用指南
    AO3中文版官网与使用指南

    AO3中文版官网入口为https://www.ao3cn.cc//,进入后点击右上角“Preferences”选择“中文(简体)”并更新即可切换语言,支持免登录浏览海量原创作品,利用标签系统精准筛选内容,平台无广告干扰且开源透明;注册账号后可发布、收藏、点赞和评论作品,并通过高级搜索功能按字数、时间等条件查找资源,实现高效互动与创作共享。

    AO3主页入口及最新镜像链接合集
    AO3主页入口及最新镜像链接合集

    AO3官方主站入口为https://www.ao3cn.cc//,提供作品发布、隐私设置、个人书架、评论管理等功能;支持多语言与移动端浏览,具备高级搜索和标签评级系统;镜像站点如https://ao3.cubeart.club/和https://xiaozhan.icu/仅作临时备用,不可输入账号密码。

    AO3官网中文入口最新地址公布
    AO3官网中文入口最新地址公布

    AO3官网中文访问入口为https://www.ao3cn.cc/,用户可直接通过主流浏览器访问,支持多语言切换至中文界面,新用户需通过邀请注册,老用户可直接登录,平台汇聚全球同人小说、画作与视频,支持自主上传与标签分类,便于检索与收藏,建议使用官方链接避免镜像站,结合筛选功能与书签快捷访问提升体验。

    AO3中文入口及官方镜像链接
    AO3中文入口及官方镜像链接

    AO3网页版中文入口为https://www.ao3cn.cc/,用户可直接访问官网注册登录,切换中文界面后使用多维度标签筛选、下载作品、互动评论等功能,享受无广告、隐私安全的非盈利创作平台。

    LibreOffice怎么卸载干净?残留配置怎么清理
    LibreOffice怎么卸载干净?残留配置怎么清理

    卸载LibreOffice应先使用系统的应用管理或原安装渠道移除程序,再按需要处理用户配置。模板、个人词典、宏和恢复备份可能保存在配置目录中,清理前先备份;普通文档不属于程序残留,不要为了“卸载干净”一起删除。以下主流程适用于Windows和Debian、Ubuntu仓库版。

    WorkBuddy怎么下载?电脑端和手机端在哪里安装
    WorkBuddy怎么下载?电脑端和手机端在哪里安装

    WorkBuddy 下载方法:电脑端从官网 workbuddy.cn 点「立即下载」获取安装包(Windows 装 exe、Mac 按 M 系列/Intel 芯片选 ARM64/X64 的 dmg),Linux 与麒麟/UOS 在系统应用商店搜索安装;手机端 iOS 在 App Store、Android 在应用市场搜「WorkBuddy」。本文含官网下载页与安装向导真实截图。

    WorkBuddy怎么用版本历史?误删了怎么恢复
    WorkBuddy怎么用版本历史?误删了怎么恢复

    WorkBuddy 的版本历史通过对话回退实现:把鼠标悬停在你发送的消息上,点「回退」并确认,对话和受影响的产物会一起回到这条消息之前;产物还有独立的历史版本,误改可在「变更」视图核对、用「恢复」还原。误删文件优先去系统回收站/废纸篓找,误删任务可在「系统设置 → 数据管理」查看已归档任务。本文含5张真实界面截图与恢复顺序表。

    Yandex引擎入口2026最新登录方式
    Yandex引擎入口2026最新登录方式

    Yandex搜索引擎的官方登录入口是https://www.yondex.net/,该平台支持多语言界面切换、智能语言识别与音译转换,并提供个性化服务及高效检索技术,满足全球用户需求。

    Yandex俄罗斯官网入口及最新搜索地址
    Yandex俄罗斯官网入口及最新搜索地址

    Yandex俄罗斯官网直达入口为https://www.yondex.net/,该平台提供网页搜索、地图导航、新闻聚合、图片视频检索等服务,支持多语言及本地化内容,集成邮箱、云存储、电商比价等生态功能。

    查看更多
    精品专题 更多
    装机必备
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows
    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程
    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版
    macOS

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版
    Windows

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。