首先把需要用到的 文本.txt 放入profile文件夹
修改ability_main.xml文件
<?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:text1"
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_ability_main"
ohos:layout_alignment="horizontal_center"
ohos:text="$string:mainability_HelloWorld"
ohos:text_size="40vp"
ohos:multiple_lines="true"
/>
<Button
ohos:id="$+id:but1"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="点我"
ohos:text_size="100"
ohos:background_element="#FFD76767"/>
</DirectionalLayout>
MainAbilitySlice.java整体代码:
package com.example.listenapplicantion7.slice;
import com.example.listenapplicantion7.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 MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
String[] jokes;
Button but1;
Text text1;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
try {
//3.用来拼接读取到的所有数据
StringBuilder sb = new StringBuilder();
//1.资源管理器
Resource resource = this.getResourceManager().getResource(ResourceTable.Profile_joke);
//2.因为resource是一个字节流,利用字节流可以读取文件中的内容
BufferedReader br = new BufferedReader(new InputStreamReader(resource));
String line;
while ((line = br.readLine()) != null){
sb.append(line);
}
//4.释放资源
br.close();
//至此,joke.txt全部读入sb当中了
//5.利用---将所有数据进行切割,分成四个段子
jokes = sb.toString().split("---");
//6.当我们点击按钮之后,给文本框设置随机的一个笑话
//找到文本,按钮组件
but1 = (Button) findComponentById(ResourceTable.Id_but1);
text1 = (Text) findComponentById(ResourceTable.Id_text1);
//7.给按钮添加单击事件
but1.setClickedListener(this);
} catch (IOException e) {
e.printStackTrace();
} catch (NotExistException e) {
e.printStackTrace();
}
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
@Override
public void onClick(Component component) {
//点击按钮后,从数据获取随机笑话,设置到文本当中
//获取随机索引
Random r = new Random();
int index = r.nextInt(jokes.length);
//通过索引获取段子
String randomJoke = jokes[index];
//把随机的段子设置到文本当中
text1.setText(randomJoke);
}
}
实现功能:每点击一次按钮随机更换一段文章