|
鸿蒙应用:在线电子词典练习部分分享, 前期部分效果图
代码如下:
<?xml version=“1.0“ encoding=“utf-8“?>
<Directionallayout
xmlns:ohos=“http://schemas.huawei.com/res/ohos“
ohos:height=“match_parent“
ohos:width=“match_parent“
ohos:orientation=“vertical“>
<DirectionalLayout
ohos:height=“match_parent“
ohos:width=“match_parent“
ohos:left_margin=“200vp“
ohos:right_margin=“200vp“
ohos:top_margin=“20vp“
ohos:orientation=“vertical“>
<DirectionalLayout
ohos:height=“50vp“
ohos:width=“match_parent“
ohos:orientation=“horizontal“>
<TextField
ohos:id=“$+id:jltftextfield_word“
ohos:height=“match_content“
ohos:width=“match_parent“
ohos:hint=“请输入要查询的单词“
ohos:background_element=“$graphic:border“
ohos:weight=“1“
ohos:padding=“4vp“
ohos:text_size=“30“/>
<Button
ohos:id=“$+id:jltfbutton_search“
ohos:height=“30vp“
ohos:width=“100vp“
ohos:text=“搜索“
ohos:scale_mode=“zoom_center“/>
</DirectionalLayout>
<Text
ohos:id=“$+id:jltftext_search_result“
ohos:height=“200vp“
ohos:width=“match_parent“
ohos:multiple_lines=“true“
ohos:visibility=“hide“
ohos:top_margin=“10vp“
ohos:text_alignment=“left|top“
ohos:text_size=“20vp“
/>
<Image
ohos:id=“$+id:jltfimage“
ohos:weight=“1“
ohos:height=“match_parent“
ohos:width=“match_parent“
ohos:image_src=“$media:index3“
ohos:scale_mode=“zoom_center“/>
</DirectionalLayout>
</DirectionalLayout>
提取本地词库
代码如下:
新建一个包一个类(电子词典类)
package com.example.jltfzidian.common;
import ohos.app.AbilityContext;
import ohos.global.resource.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
public class jltfmydict {
private AbilityContext context;
private File jltfdictpath;
private File jltfdbpath;
public jltfmydict(AbilityContext context){
this.context = context;
jltfdictpath = new File(context.getDatabaseDir().toString() +
“/MainAbility/databases/db“);
if (!jltfdictpath.exists()){
jltfdictpath.mkdirs();
}
jltfdbpath = new
File(Paths.
get(jltfdbpath.toString(),“edictshujuku.sql“).toString());
}
private void jltfextractdb() throws IOException{
//读取edictshujuku.sql文件的字节流
Resource resource =
context.getResourceManager().getRawFileEntry(“resoutces/rawfile/edictshujuku.sql“).openRawFile();
if (jltfdbpath.exists()){
jltfdbpath.delete();
}
FileOutputStream jltffos = new FileOutputStream(jltfdbpath);
byte[] jltfbuffer = new byte[4096];
int count = 0;
while ((count = resource.read(jltfbuffer))>= 0){
jltffos.write(jltfbuffer,0,count);
}
resource.close();
jltffos.close();
}
public void init() throws IOException{
jltfextractdb();
}
}
MainAbilitySlice中 添加如下代码
mydict = new jltfmydict(this);
try {
mydict.init();
}catch (IOException e){
terminateAbility();
}
}
本练习参考了李宁老师公开的代码与课程。 |
|