base/profile下存放一个joke.txt文件
里面又三个笑话并且用---分割
“大爷,我现场采访您一下,您这样晨跑锻炼坚持几年了?”
“姑娘别挡道!我尿急! ”
“请问你是做什么工作的?”
---
“哦。我的工作是杀僵尸。”
“嗯?可是这个世界上没有僵尸啊! ”
“你以为它们是怎么没有的?”
---
中午去买菜,感觉都不太新鲜了。
老板:早上刚到的,都新鲜的。
我:这菜看着就蔫蔫的啊?!
老板:从早上到现在,它以为没人要自己了,这不垂头丧气么!
我。。。
布局
<?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:alignment="center"
ohos:orientation="vertical">
<Text
ohos:id="$+id:joke"
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_ability_joke"
ohos:layout_alignment="horizontal_center"
ohos:multiple_lines="true"
ohos:text="$string:jokeability_HelloWorld"
ohos:text_size="40vp"
/>
<Button
ohos:id="$+id:btnReadRandom"
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_ability_joke"
ohos:layout_alignment="horizontal_center"
ohos:text="读取随机笑话"
ohos:text_size="40vp"
/>
</DirectionalLayout>
? ? ?ohos:multiple_lines="true" 允许换行
代码
package com.example.helloworld.slice;
import com.example.helloworld.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class JokeAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_joke);
Text text = findComponentById(ResourceTable.Id_joke);
Button btnReadRandom = findComponentById(ResourceTable.Id_btnReadRandom);
StringBuilder sb = new StringBuilder();
try {
//返回文件的字节流
Resource resource = this.getResourceManager().getResource(ResourceTable.Profile_joke);
//字节流
BufferedReader br = new BufferedReader(new InputStreamReader(resource));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
} catch (NotExistException e) {
e.printStackTrace();
}
btnReadRandom.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
String[] jocks = sb.toString().split("---");
Random random = new Random();
int index = random.nextInt(jocks.length);
text.setText(jocks[index]);
}
});
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
?
|