官方总结鸿蒙应用开发常见问题与实现方法典型案例
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的布局文件
<?xml version="1.0" encoding="utf-8"?> <DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:width="match_parent" ohos:height="match_content" ohos:padding="10vp" ohos:background_element="@graphic:grey" ohos:orientation="vertical"> <Text ohos:width="match_parent" ohos:height="match_content" ohos:text="Dialog标题" ohos:text_color="$color:Black" ohos:text_style="bold" ohos:text_size="40fp"/> <Text 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"/> <DirectionalLayout ohos:height="match_content" ohos:width="match_parent" ohos:orientation="horizontal"> <Button 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"/> <Button 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"/> </DirectionalLayout> </DirectionalLayout>
1.3 实际效果
2 设置控件背景颜色
2.1 问题描述
在xml布局中设置控件ohos:background_element="$color:yellow"无效,目前背景颜色不支持以$color方式设置,只支持$graphic方式设置。
2.2 实现方法
方式1:xml中设置控件背景颜色使用$graphic
<Button 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代码如下:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:shape="rectangle"> <solid ohos:color="#fff9a825"/> </shape>
方式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 实现方法
- 使用xml布局,需要将ScrollView的高度设置成“match_parent”,ScrollView子布局的高度设置成“match_content”
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:width="match_parent" ohos:height="match_parent" ohos:orientation="vertical"> <DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:width="match_parent" ohos:height="match_content" ohos:orientation="vertical"> ... </DirectionalLayout> </ScrollView>
- 使用代码添加,则需要给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 实现方法
- 在config.json中添加网络权限
{ "module": { "reqPermissions": [ { "name": "ohos.permission.INTERNET" } ] } }
- 获取并设置网络图片
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文件中声明组件
<?xml version="1.0" encoding="utf-8"?> <DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:width="match_parent" ohos:height="match_parent" ohos:orientation="vertical"> <ListContainer ohos:id="$+id:list_container" ohos:orientation="vertical" ohos:width="match_parent" ohos:height="match_parent"/> </DirectionalLayout>
获取 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 实现方法
- 对于图片文件,建议放到base/media目录下,Image组件可以直接设置,方法如下。
Image image = (Image) findComponentById(ResourceTable.Id_component_image); image.setPixelMap(ResourceTable.Media_huawei);
- 对于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 实现方法
- 导入获取位置模块,并调用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"); } }); } }
- 在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 实现方法
可以使用系统自动换行,保持两行文字长度一致,实现如下
<?xml version="1.0" encoding="utf-8"?> <DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:width="match_parent" ohos:height="match_parent" ohos:orientation="vertical"> <Text 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="目前车辆尊享服务已过期, 车主续费后才可继续使用"/> </DirectionalLayout>
9.3 实际效果
10 在一个布局xml中引入其他xml布局文件
10.1 问题描述
定义了一个公共的XML布局文件,如何在其他XML布局文件中引用这个公共的XML布局文件?
10.2 实现方法
可以通过include标签引用其他的XML布局文件,示例如下:
<?xml version="1.0" encoding="utf-8"?> <include ohos:id="$+id:include_layout" ohos:layout="$layout:include_layout" ohos:width="match_parent" ohos:height="match_content"/> </DirectionalLayout>
10.3 实际效果
NA
11 自定义Swtich控件的颜色
11.1 问题描述
如何自定义Swtich控件的开关两个状态下的按钮颜色?
11.2 实现方法
在资源文件graphic文件下创建bg_element.xml和fg_element.xml,bg_element.xml文件内容如下
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:shape="rectangle"> <corners ohos:radius="30"/> <solid ohos:color="#424242"/> </shape>
fg_element.xml文件内容如下
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:shape="oval"> <solid ohos:color="#D81B60"/> </shape>
代码实现自定义颜色:
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,内容如下
<?xml version="1.0" encoding="utf-8"?> <DependentLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:id="$+id:video_player_dl" ohos:width="match_parent" ohos:height="match_parent" ohos:orientation="vertical"> </DependentLayout>
定义下面的变量,内容如下:
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 实际效果
原文链接:https://developer.huawei.com/consumer/cn/forum/topic/0204410755673870341?fid=0101303901040230869
原作者:eva3w

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
云原生(cloud native)是什么,怎么理解
很多人都会问“到底什么是云原生”,对此,CNCF 官方大使、阿里云容器平台高级技术专家张磊曾经做过精彩的解释。 实际上,云原生是一条最佳路径或者最佳实践。更详细的说,云原生为用户指定了一条低心智负担的、敏捷的、能够以可扩展、可复制的方式最大化地利用云的能力、发挥云的价值的最佳路径。 因此,云原生其实是一套指导进行软件架构设计的思想。按照这样的思想而设计出来的软件:首先,天然就“生在云上,长在云上”;其次,能够最大化地发挥云的能力,使得我们开发的软件和“云”能够天然地集成在一起,发挥出“云”的最大价值。 所以,云原生最大的价值和愿景,就是认为未来的软件,会从诞生起就生长在云上,并且遵循一种新的软件开发、发布和运维模式,从而使得软件能够最大化地发挥云的能力。说到了这里,你也可以思考一下为什么容器技术具有革命性? 其实,容器技术和集装箱技术的革命性非常类似,即:容器技术使得应用具有了一种“自包含”的定义方式。所以,这样的应用才能以敏捷的、以可扩展可复制的方式发布在云上,发挥出云的能力。这也就是容器技术对云发挥出的革命性影响所在,所以说,容器技术正是云原生技术的核心底盘。 云原生的技术范畴 云...
- 下一篇
Serverless 在编程教育中的实践
说起Serverless这个词,我想大家应该都不陌生,那么Serverless这个词到底是什么意思?Serverless到底能解决什么问题?可能很多朋友还没有深刻的体会和体感,这篇文章我就和大家一起聊聊Serverless。 什么是Serverless 我们先将Serverless这个词拆开来看。Server,大家都知道是服务器的意思,说明Serverless解决的问题范围在服务端。Less,大家肯定也知道它的意思是较少的。那么Serverless连起来,再稍加修饰,那就是较少的关心服务器的意思。 Serverfull时代 我们都知道,在研发侧都会有研发人员和运维人员两个角色,要开发一个新系统的时候,研发人员根据产品经理的PRD开始写代码开发功能,当功能开发、测试完之后,要发布到服务器。这个时候开始由运维人员规划服务器规格、服务器数量、每个服务部署的节点数量、服务器的扩缩容策略和机制、发布服务过程、服务优雅上下线机制等等。这种模式是研发和运维隔离,服务端运维都由专门的运维人员处理,而且很多时候是靠纯人力处理,也就是Serverfull时代。 DevOps时代 互联网公司里最辛苦的是谁?...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- Hadoop3单机部署,实现最简伪集群
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- CentOS7编译安装Gcc9.2.0,解决mysql等软件编译问题
- SpringBoot2配置默认Tomcat设置,开启更多高级功能
- SpringBoot2整合Redis,开启缓存,提高访问速度
- Windows10,CentOS7,CentOS8安装Nodejs环境
- MySQL8.0.19开启GTID主从同步CentOS8
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- Eclipse初始化配置,告别卡顿、闪退、编译时间过长
- 设置Eclipse缩进为4个空格,增强代码规范