鴻蒙「3.4 熟知的列表」闖蕩HAP之單-列表和組裝列表
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)
https://harmonyos.51cto.com/#zz
- 在一個文件夾里會羅列出很多個子文件夾或者文件,包含文件名、文件大小、文件修改日期、文件類型等;
- 在一個內(nèi)容網(wǎng)站里會羅列出很多條內(nèi)容,或許還要翻頁,包含文章標(biāo)題、文章作者、發(fā)表時間、瀏覽量等;
- 在一個圖冊網(wǎng)站,里面會羅列出很多圖集或者圖片,包含圖集名稱、圖集作者等;
- 在一個音樂播放器的具體某類歌曲中,會羅列出很多歌曲,包含歌名、作者、所屬歌集、時長等;
還有很多想類似的情況,這里就不一一列舉了。通過上面四個場景,我們可以發(fā)現(xiàn)一個共同的特點,它們都有很多條數(shù)據(jù),每個場景中數(shù)據(jù)的屬性是相同的。這就讓我想起了在學(xué)習(xí)Java 的數(shù)組時,對于一維數(shù)組,其元素的類型是相同的,你不可能定義了一個整形的數(shù)組,向里面添加了字符串類型的元素,這是不行的。假如我們需要做一個新聞類的展示界面,那么我們的數(shù)據(jù)中,每個元素中的屬性必須是一樣的。比如我們的元素屬性包含標(biāo)題、作者、內(nèi)容摘要、封面圖、發(fā)布時間、瀏覽記錄、點贊量、評論量,但是在這個列表中存在一個特殊的元素,它的屬性為歌曲名稱、作者、歌集、時長,那么我們在展示這個數(shù)據(jù)集的時候,會出現(xiàn)什么問題呢(這里不做詳細(xì)說明了,也許你已經(jīng)知道答案是什么了)?
對于ListContainer組件的理論不在這里做贅述了,官文已經(jīng)說得很明白了,本節(jié)將結(jié)合OkHttp插件,來使用ListContainer組件做一個簡單的新聞?wù)故綝emo。
在開始復(fù)雜的列表展示頁之前,我們先來做一個簡單的列表展示,在學(xué)習(xí)Android的時候,列表有個展示水果的示例,我將在HarmonyOS智慧屏上實現(xiàn)這個小示例。
一、單一的列表
1、在layout目錄下新建fruit_layout.xml文件,并創(chuàng)建ListContainer組件,代碼如下:
- <?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">
- <ListContainer
- ohos:id="$+id:fruit_list"
- ohos:height="match_parent"
- ohos:width="match_parent"
- ohos:layout_alignment="horizontal_center"/>
- </DirectionalLayout>
2、接著在layout目錄新建element_layout.xml文件,作為ListContainer組件的子布局,代碼如下:
- <?xml version="1.0" encoding="utf-8"?>
- <DirectionalLayout
- xmlns:ohos="http://schemas.huawei.com/res/ohos"
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:background_element="$graphic:background_element"
- ohos:bottom_margin="4vp"
- ohos:orientation="vertical">
- <Text
- ohos:id="$+id:element_index"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:padding="4vp"
- ohos:text_size="30fp"
- ohos:layout_alignment="center"/>
- </DirectionalLayout>
3、組建一個類型為String的List列表,最終呈現(xiàn)在UI界面上。
- List<String> fruits = new ArrayList<>();
- fruits.add("蘋果");
- fruits.add("橘子");
- fruits.add("橙子");
- fruits.add("香蕉");
- fruits.add("梨");
- fruits.add("桃子");
- fruits.add("蘋果梨");
- fruits.add("香蕉梨");
- fruits.add("冬桃");
- fruits.add("紅葡萄");
- fruits.add("紫葡萄");
- fruits.add("黑葡萄");
4、ListContainer組件的每一行元素可以是不相同的數(shù)據(jù),因此需要適配不同的數(shù)據(jù)結(jié)構(gòu),使其能夠添加到ListContainer組件中,并以列表的形式呈現(xiàn)在UI界面上。ListContainer組件提供了setItemProvider(BaseItemProvider itemProvider)方法,用于設(shè)置要顯示的ListContainer組件對象。創(chuàng)建FruitElementProvider類,并繼承BaseItemProvider,重寫其中的方法。
- package com.ming.harmonyos.newsapp.domain;
- import com.ming.harmonyos.newsapp.ResourceTable;
- import ohos.aafwk.ability.AbilitySlice;
- import ohos.agp.components.*;
- import java.util.List;
- public class FruitElementProvider extends BaseItemProvider {
- private List<String> list;
- private AbilitySlice slice;
- public FruitElementProvider(List<String> fruits, AbilitySlice slice) {
- this.list = fruits;
- this.slice = slice;
- }
- @Override
- public int getCount() {
- return list.size();
- }
- @Override
- public Object getItem(int i) {
- return list.get(i);
- }
- @Override
- public long getItemId(int i) {
- return i;
- }
- @Override
- public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
- Component cpt = component;
- if (cpt == null) {
- cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_element_layout, null, false);
- }
- String fruit = list.get(i);
- Text text = (Text) cpt.findComponentById(ResourceTable.Id_element_index);
- text.setText(fruit);
- return cpt;
- }
- }
5、在MainAbility中適配ListContainer的數(shù)據(jù)結(jié)構(gòu),并添加點擊事件。
- ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_fruit_list);
- List<String> fruits = new ArrayList<>();
- fruits.add("蘋果");
- fruits.add("橘子");
- fruits.add("橙子");
- fruits.add("香蕉");
- fruits.add("梨");
- fruits.add("桃子");
- fruits.add("蘋果梨");
- fruits.add("香蕉梨");
- fruits.add("冬桃");
- fruits.add("紅葡萄");
- fruits.add("紫葡萄");
- fruits.add("黑葡萄");
- FruitElementProvider fruitElementProvider = new FruitElementProvider(fruits, this);
- listContainer.setItemProvider(fruitElementProvider);
- listContainer.setItemClickedListener((listContainer1, component, position, id) -> {
- String item = (String) listContainer1.getItemProvider().getItem(position);
- new ToastDialog(getContext())
- .setText("點擊了:" + item)
- // Toast顯示在界面中間
- .setAlignment(LayoutAlignment.CENTER)
- .show();
- });
6、運(yùn)行查看效果。
二、組合復(fù)雜的列表
1、和單一列表不同之處在于元素的顯示和元素的屬性。單一列表中我使用了一個List
1)首先我們在build.gradle中引入OkHttp(本節(jié)并不是對OkHttp做詳細(xì)講解,這里只是簡單的使用)的版本,并點擊窗口上的Sync Now進(jìn)行同步下載。
- implementation("com.squareup.okhttp3:okhttp:4.9.0")
2)在config.json中配置INTENT權(quán)限。
- "reqPermissions": [
- {
- "name": "ohos.permission.INTERNET",
- "usedScene": {
- "ability": [
- "com.ming.harmonyos.newsapp.MainAbility"
- ],
- "when": "always"
- }
- }
- ]
3)在MainAbilitySlice中實例化OkHttpClient對象,并封裝它的GET調(diào)用方法。
- private OkHttpClient client = new OkHttpClient();
- private String run(String url) throws IOException {
- Request request = new Request.Builder()
- .url(url)
- .build();
- try (Response response = client.newCall(request).execute()) {
- return response.body().string();
- }
- }
2、做好上面的準(zhǔn)備之后,我使用天行數(shù)據(jù)的每日簡報API接口。先看一下調(diào)用接口返回的參數(shù):
3、我們根據(jù)返回的參數(shù)來構(gòu)建我們的列表元素類。
- public class News {
- //新聞標(biāo)題
- private String title;
- //簡報內(nèi)容
- private String digest;
- //簡報封面
- private String imgsrc;
- //簡報鏈接
- private String url;
- //簡報來源
- private String source;
- //新聞時間
- private String mtime;
- //getter & setter
- }
4、在layout目錄新建news_element_layout.xml文件,作為ListContainer組件的子布局,代碼如下:
- <?xml version="1.0" encoding="utf-8"?>
- <DirectionalLayout
- xmlns:ohos="http://schemas.huawei.com/res/ohos"
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:bottom_margin="4vp"
- ohos:orientation="vertical">
- <DirectionalLayout
- ohos:height="match_parent"
- ohos:width="match_parent"
- ohos:background_element="$graphic:background_element"
- ohos:orientation="horizontal">
- <Image
- ohos:id="$+id:news_imgsrc"
- ohos:image_src="$media:icon"
- ohos:height="100vp"
- ohos:width="100vp"/>
- <DirectionalLayout
- ohos:height="match_parent"
- ohos:width="match_parent">
- <Text
- ohos:id="$+id:news_title"
- ohos:height="match_parent"
- ohos:width="match_parent"
- ohos:weight="1"
- ohos:text="我是標(biāo)題"
- ohos:text_size="20fp"/>
- <Text
- ohos:id="$+id:news_remark"
- ohos:height="match_parent"
- ohos:width="match_parent"
- ohos:weight="1"
- ohos:text="我是摘要"
- ohos:text_size="14fp"
- ohos:multiple_lines="true"
- ohos:max_text_lines="2"
- ohos:text_color="#888888"/>
- <DependentLayout
- ohos:height="match_parent"
- ohos:width="match_parent"
- ohos:weight="1">
- <Text
- ohos:id="$+id:news_source"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:text="來源"
- ohos:text_size="12fp"
- ohos:text_color="#CCCCCC"
- ohos:align_parent_left="true"/>
- <Text
- ohos:id="$+id:news_time"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:text="時間"
- ohos:text_size="12fp"
- ohos:text_color="#CCCCCC"
- ohos:right_padding="20vp"
- ohos:align_parent_right="true"/>
- </DependentLayout>
- </DirectionalLayout>
- </DirectionalLayout>
- </DirectionalLayout>
5、創(chuàng)建NewsItemProvider類,并繼承BaseItemProvider,重寫其中的方法。
- @Override
- public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
- Component cpt = component;
- if (cpt == null) {
- cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_news_element_layout, null, false);
- }
- News news = list.get(i);
- //封面圖
- Image image = (Image) cpt.findComponentById(ResourceTable.Id_news_imgsrc);
- //標(biāo)題
- Text title = (Text) cpt.findComponentById(ResourceTable.Id_news_title);
- title.setText(news.getTitle());
- //摘要
- Text remark = (Text) cpt.findComponentById(ResourceTable.Id_news_remark);
- remark.setText(news.getDigest());
- //來源
- Text source = (Text) cpt.findComponentById(ResourceTable.Id_news_source);
- source.setText(news.getSource());
- //日期
- Text time = (Text) cpt.findComponentById(ResourceTable.Id_news_time);
- time.setText(news.getMtime());
- return cpt;
- }
6、在MainAbility中使用OkHttp獲取數(shù)據(jù)并適配ListContainer的數(shù)據(jù)結(jié)構(gòu),最后查看運(yùn)行效果。
- /**
- * 復(fù)雜數(shù)據(jù)結(jié)構(gòu)
- */
- private void initNewsListContainer() {
- //在子線程中獲取數(shù)據(jù)
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- String response = MainAbilitySlice.this.run("https://api.tianapi.com/bulletin/index?key=您自己的KEY");
- System.out.println(response);
- JSONObject jsonObject = JSONObject.parseObject(response);
- int code = Integer.valueOf(String.valueOf(jsonObject.get("code")));
- String message = String.valueOf(jsonObject.get("msg"));
- String data = String.valueOf(jsonObject.get("newslist"));
- if (code == 200) {
- List<News> list = JSONArray.parseArray(data, News.class);
- ListContainer news = (ListContainer) findComponentById(ResourceTable.Id_news_list);
- NewsItemProvider nip = new NewsItemProvider(list, MainAbilitySlice.this);
- news.setItemProvider(nip);
- } else {
- new ToastDialog(getContext())
- .setText("拋出異常信息: " + message)
- .setAlignment(LayoutAlignment.CENTER)
- .show();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }).start();
- }
我的HarmonyOS GitHub庫
©著作權(quán)歸作者和HarmonyOS技術(shù)社區(qū)共同所有,如需轉(zhuǎn)載,請注明出處,否則將追究法律責(zé)任
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)
https://harmonyos.51cto.com/#zz