[文章]基于HarmonyOS Java UI,实现常见组件或者布局

阅读量0
0
5
1. 介绍   
本篇Codelab目的
本篇Codelab旨在让开发者了解HarmonyOS应用开发常用布局和常用组件的使用方法,体验从工程创建到代码、布局的编写,再到编译构建、部署和运行的全过程。
您将会学到什么
  • 如何创建一个HarmonyOS Project并添加页面布局
  • 如何使用DirectionalLayout、DependentLayout、StackLayout、TableLayout等常用布局
  • 如何使用TabList、ListContainer、DatePicker、RadioContainer、Checkbox等常用组件
硬件要求
  • 操作系统:Windows10 64位
  • 内存:8G及以上
  • 硬盘:100G及以上
  • 分辨率:1280*800像素及以上
软件要求
  • 安装DevEco Studio,详情请参考DevEco Studio下载。
  • 设置Huawei DevEco Studio开发环境,Huawei DevEco Studio开发环境需要依赖于网络环境,需要连接上网络才能确保工具的正常使用,可以根据如下两种情况来配置开发环境
    • 如果可以直接访问Internet,只需进行下载HarmonyOS SDK操作
    • 如果网络不能直接访问Internet,需要通过代理服务器才可以访问,请参考配置开发环境

    说明
    如需要在手机中运行程序,则需要提前生成秘钥和申请证书,如使用模拟器可忽略
  • 生成秘钥和申请证书,详情请参考准备签名文件
技能要求
  • Java基础开发能力
  • XML布局文件编写能力

2. 搭建HarmonyOS环境   
我们首先需要完成HarmonyOS开发环境搭建,可参照如下步骤进行。
  • 安装DevEco Studio,详情请参考下载和安装软件。
  • 设置DevEco Studio开发环境,DevEco Studio开发环境依赖于网络环境,需要连接上网络才能确保工具的正常使用,可以根据如下两种情况来配置开发环境:
    • 如果可以直接访问Internet,只需进行下载HarmonyOS SDK操作。
    • 如果网络不能直接访问Internet,需要通过代理服务器才可以访问,请参考配置开发环境。
  • 开发者可以参考以下链接,完成设备调试的相关配置:
    • 使用真机进行调试
    • 使用模拟器进行调试
3. 下载Codelab起步应用      
  • 获取Codelab起步应用ComponentCodelab,可从gitee源码或github源码下载
  • 打开HUAWEI DevEco Studio,点击File > Open选择步骤1中下载的ComponentCodelab
  • 点击Build > Build App(s)/Hap(s)>Build Debug Hap(s)构建hap包
  • 点击Run> Run ‘entry'运行hap包,可看到运行效果如下:

说明
此应用在模拟器或者真机上都可以运行。如果在真机上运行,则需要先在工程的File > Project Structure>Modules>Signing Configs中配置签名和证书信息。

4. 体验TabList和Tab组件        
Tablist可以实现多个页签栏的切换,Tab为某个页签。子页签通常放在内容区上方,展示不同的分类。页签名称应该简洁明了,清晰描述分类的内容。TabList和Tab组件的使用方法详见常用组件开发指导。        
创建module
点击工程右键,选择new-->module,如下图所示:

随后选择Empty Ability(Java)模板,Application/Library name命名为Tablist,Module Name命名为tablist,如下图:

点击Next按钮,进入Configure Ability界面,Page Name使用默认值,Layout Name命名为tab_list,如下图:

点击Finish,完成module创建。
     编写布局文件
在src/main/resources/base/layout目录下新建布局文件tab_list.xml,此布局文件中主要使用Tablist组件,并设置其样式。
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DirectionalLayout
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4.     ohos:width="match_parent"
  5.     ohos:height="match_parent"
  6.     ohos:top_margin="15vp"
  7.     ohos:orientation="vertical">
  8.     <TabList
  9.         ohos:id="$+id:tab_list"
  10.         ohos:top_margin="10vp"
  11.         ohos:tab_margin="24vp"
  12.         ohos:tab_length="140vp"
  13.         ohos:text_size="20fp"
  14.         ohos:height="36vp"
  15.         ohos:width="match_parent"
  16.         ohos:layout_alignment="center"
  17.         ohos:orientation="horizontal"
  18.         ohos:text_alignment="center"
  19.         ohos:normal_text_color="#999999"
  20.         ohos:selected_text_color="#afaafa"
  21.         ohos:selected_tab_indicator_color="#afaafa"
  22.         ohos:selected_tab_indicator_height="2vp"/>
  23.     <Text
  24.         ohos:id="$+id:tab_content"
  25.         ohos:width="match_parent"
  26.         ohos:height="match_parent"
  27.         ohos:text_alignment="center"
  28.         ohos:background_element="#70dbdb"
  29.         ohos:text_color="#2e2e2e"
  30.         ohos:text_size="16fp"/>
  31. </DirectionalLayout>
复制代码

编写AbilitySlice文件
在src/main/java/com/huawei/codelab/slice目录下新建TabListSlice.java文件,继承AbilitySlice。
定义成员变量,加载布局:
  1. private TabList tabList;
  2. private Text tabContent;

  3. [url=home.php?mod=space&uid=2735960]@Override[/url]
  4. public void onStart(Intent intent) {
  5.     super.onStart(intent);
  6.     super.setUIContent(ResourceTable.Layout_tab_list);
  7.     initComponent();
  8.     addTabSelectedListener();
  9. }
复制代码
初始化组件:
  1. private void initComponent() {
  2.     tabContent = (Text) findComponentById(ResourceTable.Id_tab_content);
  3.     tabList = (TabList) findComponentById(ResourceTable.Id_tab_list);
  4.     initTab();
  5. }

  6. private void initTab() {
  7.     if (tabList.getTabCount() == 0) {
  8.         tabList.addTab(createTab("Image"));
  9.         tabList.addTab(createTab("Video"));
  10.         tabList.addTab(createTab("Audio"));
  11.         tabList.setFixedMode(true);
  12.         tabList.getTabAt(0).select();
  13.         tabContent.setText("Select the " + tabList.getTabAt(0).getText());
  14.     }
  15. }

  16. private TabList.Tab createTab(String text) {
  17.     TabList.Tab tab = tabList.new Tab(this);
  18.     tab.setText(text);
  19.     tab.setMinWidth(64);
  20.     tab.setPadding(12, 0, 12, 0);
  21.     return tab;
  22. }
复制代码
绑定点击事件:
  1. private void addTabSelectedListener() {
  2.     tabList.addTabSelectedListener(new TabList.TabSelectedListener() {
  3.         @Override
  4.         public void onSelected(TabList.Tab tab) {
  5.             tabContent.setText("Select the " + tab.getText());
  6.         }

  7.         @Override
  8.         public void onUnselected(TabList.Tab tab) {
  9.         }

  10.         @Override
  11.         public void onReselected(TabList.Tab tab) {
  12.         }
  13.     });
  14. }
复制代码
运行程序
点击Run> Run 'tablist'运行hap包,进入到程序主页,点击主页的TabList and Tab即可看到TabList页面,点击页面上方不同的Tab,页面内容将同步变化。效果如下所示:
   
5. 体验ListContainer组件        
ListContainer是用来呈现连续、多行数据的组件,包含一系列相同类型的列表项。ListContainer组件的使用方法详见常用组件开发指导。在本章节,我们将利用ListContainer组件编写一个新闻首页界面,上方的新闻类别和中间的新闻列表都将使用ListContainer组件来实现。        
创建module
可参考3.1创建步骤,其中Application/Library name命名为ListContainer,Module Name命名为Listcontainer,Layout Name命名为news_list_layout。
     编写布局文件
在src/main/resources/base/layout目录下新建布局文件news_list_layout.xml作为新闻列表主界面,并设置其样式。
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DirectionalLayout
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4.     ohos:height="match_parent"
  5.     ohos:width="match_parent"
  6.     ohos:orientation="vertical">
  7.     <ListContainer
  8.         ohos:id="$+id:selector_list"
  9.         ohos:height="36vp"
  10.         ohos:width="match_parent"
  11.         ohos:top_padding="8vp"
  12.         ohos:orientation="horizontal"/>
  13.     <Component
  14.         ohos:height="1vp"
  15.         ohos:width="match_parent"
  16.         ohos:background_element="#70dbdb"/>
  17.     <ListContainer
  18.         ohos:id="$+id:news_container"
  19.         ohos:height="match_parent"
  20.         ohos:width="match_parent"/>
  21. </DirectionalLayout>
复制代码
在src/main/resources/base/layout目录下新建布局文件item_news_type_layout.xml作为上方的新闻类别的item详情布局。
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DirectionalLayout
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4.     ohos:height="40vp"
  5.     ohos:width="match_content">
  6.     <Text
  7.         ohos:id="$+id:news_type_text"
  8.         ohos:height="match_content"
  9.         ohos:width="match_content"
  10.         ohos:text_alignment="center"
  11.         ohos:left_padding="20vp"
  12.         ohos:right_padding="20vp"
  13.         ohos:text_color="#55000000"
  14.         ohos:text_size="16fp"/>
  15. </DirectionalLayout>
复制代码
在src/main/resources/base/layout目录下新建布局文件item_news_layout.xml作为中间的新闻列表的item详情布局。
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DirectionalLayout
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4.     ohos:height="110vp"
  5.     ohos:width="match_parent"
  6.     ohos:orientation="vertical">
  7.     <DirectionalLayout
  8.         ohos:height="109vp"
  9.         ohos:width="match_parent"
  10.         ohos:orientation="horizontal"
  11.         ohos:padding="10vp">
  12.         <Text
  13.             ohos:id="$+id:item_news_title"
  14.             ohos:height="match_content"
  15.             ohos:width="0vp"
  16.             ohos:max_text_lines="3"
  17.             ohos:multiple_lines="true"
  18.             ohos:right_padding="20vp"
  19.             ohos:text_size="18vp"
  20.             ohos:weight="2"/>
  21.         <Image
  22.             ohos:id="$+id:item_news_image"
  23.             ohos:height="match_content"
  24.             ohos:width="0vp"
  25.             ohos:image_src="$media:news_image"
  26.             ohos:weight="1"/>
  27.     </DirectionalLayout>
  28.     <Component
  29.         ohos:height="1vp"
  30.         ohos:width="match_parent"
  31.         ohos:background_element="#70dbdb"/>
  32. </DirectionalLayout>
复制代码
编写Provider文件在src/main/java/com/huawei/codelab/provider目录下新建NewsTypeProvider.java文件,构造新闻类别的Provider。
  1. public class NewsTypeProvider extends BaseItemProvider {
  2.     private String[] newsTypeList;
  3.     private Context context;

  4.     public NewsTypeProvider(String[] listBasicInfo, Context context) {
  5.         this.newsTypeList = listBasicInfo;
  6.         this.context = context;
  7.     }

  8.     @Override
  9.     public int getCount() {
  10.         return newsTypeList == null ? 0 : newsTypeList.length;
  11.     }

  12.     @Override
  13.     public Object getItem(int position) {
  14.         return Optional.of(this.newsTypeList[position]);
  15.     }

  16.     @Override
  17.     public long getItemId(int position) {
  18.         return position;
  19.     }

  20.     @Override
  21.     public Component getComponent(int position, Component componentP, ComponentContainer componentContainer) {
  22.         ViewHolder viewHolder = null;
  23.         Component component = componentP;
  24.         if (component == null) {
  25.             component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item_news_type_layout, null, false);
  26.             viewHolder = new ViewHolder();
  27.             Component componentText = component.findComponentById(ResourceTable.Id_news_type_text);
  28.             if (componentText instanceof Text) {
  29.                 viewHolder.title = (Text) componentText;
  30.             }
  31.             component.setTag(viewHolder);
  32.         } else {
  33.             if (component.getTag() instanceof ViewHolder) {
  34.                 viewHolder = (ViewHolder) component.getTag();
  35.             }
  36.         }
  37.         if (viewHolder != null) {
  38.             viewHolder.title.setText(newsTypeList[position]);
  39.         }
  40.         return component;
  41.     }

  42.     private static class ViewHolder {
  43.         Text title;
  44.     }
  45. }
复制代码
在src/main/java/com/huawei/codelab/provider目录下新建NewsListProvider.java文件,构造新闻列表的Provider。
  1. public class NewsListProvider extends BaseItemProvider {
  2.     private List<NewsInfo> newsInfoList;
  3.     private Context context;

  4.     public NewsListProvider(List<NewsInfo> listBasicInfo, Context context) {
  5.         this.newsInfoList = listBasicInfo;
  6.         this.context = context;
  7.     }

  8.     @Override
  9.     public int getCount() {
  10.         return newsInfoList == null ? 0 : newsInfoList.size();
  11.     }

  12.     @Override
  13.     public Object getItem(int position) {
  14.         return Optional.of(this.newsInfoList.get(position));
  15.     }

  16.     @Override
  17.     public long getItemId(int position) {
  18.         return position;
  19.     }

  20.     @Override
  21.     public Component getComponent(int position, Component componentP, ComponentContainer componentContainer) {
  22.         ViewHolder viewHolder = null;
  23.         Component component = componentP;
  24.         if (component == null) {
  25.             component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item_news_layout, null, false);
  26.             viewHolder = new ViewHolder();
  27.             Component componentTitle = component.findComponentById(ResourceTable.Id_item_news_title);
  28.             Component componentImage = component.findComponentById(ResourceTable.Id_item_news_image);
  29.             if (componentTitle instanceof Text) {
  30.                 viewHolder.title = (Text) componentTitle;
  31.             }
  32.             if (componentImage instanceof Image) {
  33.                 viewHolder.image = (Image) componentImage;
  34.             }
  35.             component.setTag(viewHolder);
  36.         } else {
  37.             if (component.getTag() instanceof ViewHolder) {
  38.                 viewHolder = (ViewHolder) component.getTag();
  39.             }
  40.         }
  41.         if (viewHolder != null) {
  42.             viewHolder.title.setText(newsInfoList.get(position).getTitle());
  43.             viewHolder.image.setScaleMode(Image.ScaleMode.STRETCH);
  44.         }
  45.         return component;
  46.     }

  47.     private static class ViewHolder {
  48.         Text title;
  49.         Image image;
  50.     }
  51. }
复制代码
编写AbilitySlice文件在src/main/java/com/huawei/codelab/slice目录下新建ListContainerSlice.java文件,继承AbilitySlice。
定义成员变量,加载布局:
  1. private static final float FOCUS_TEXT_SIZE = 1.2f;
  2. private static final float UNFOCUS_TEXT_SIZE = 1.0f;
  3. private Text selectText;
  4. private ListContainer newsListContainer;
  5. private ListContainer selectorListContainer;
  6. private List<NewsInfo> totalNews;
  7. private List<NewsInfo> selectNews;
  8. private NewsTypeProvider newsTypeProvider;
  9. private NewsListProvider newsListProvider;

  10. @Override
  11. public void onStart(Intent intent) {
  12.     super.onStart(intent);
  13.     super.setUIContent(ResourceTable.Layout_news_list_layout);
  14.     initView();
  15.     initProvider();
  16.     setListContainer();
  17.     initListener();
  18. }
复制代码
初始化组件:

  1. private void initView() {
  2.     selectorListContainer = (ListContainer) findComponentById(ResourceTable.Id_selector_list);
  3.     newsListContainer = (ListContainer) findComponentById(ResourceTable.Id_news_container);
  4. }
复制代码
使用POJO类封装数据源中与每个列表项对应的数据:
  1. public class NewsInfo {
  2.     private String title;
  3.     private String type;

  4.     public String getTitle() {
  5.         return title;
  6.     }

  7.     public void setTitle(String title) {
  8.         this.title = title;
  9.     }

  10.     public String getType() {
  11.         return type;
  12.     }

  13.     public void setType(String type) {
  14.         this.type = type;
  15.     }
  16. }
复制代码
初始化Provider:
  1. private void initProvider() {
  2.     String[] listNames = new String[]{"All", "Health", "Finance", "Technology", "Sport", "Internet", "Game"};
  3.     newsTypeProvider = new NewsTypeProvider(listNames, this);
  4.     newsTypeProvider.notifyDataChanged();

  5.     String[] newsTypes = new String[]{"Health", "Finance", "Finance", "Technology", "Sport", "Health", "Internet", "Game", "Game", "Internet"};
  6.     String[] newsTitles = new String[]{
  7.         "Best Enterprise Wi-Fi Network Award of the Wireless Broadband Alliance 2020",
  8.         "Openness and Cooperation Facilitate Industry Upgrade",
  9.         "High-voltage super-fast charging is an inevitable trend",
  10.         "Ten Future Trends of Digital Energy",
  11.         "Ascend Helps Industry, Learning, and Research Promote AI Industry Development in the National AI Contest",
  12.         "Enterprise data centers are moving towards autonomous driving network",
  13.         "One optical fiber lights up a green smart room",
  14.         "Trust technology, embrace openness, and share the world prosperity brought by technology",
  15.         "Intelligent Twins Won the Leading Technology Achievement Award at the 7th World Internet Conference",
  16.         "Maximizing the Value of Wireless Networks and Ushering in the Golden Decade of 5G"
  17.     };
  18.     totalNews = new ArrayList<>();
  19.     selectNews = new ArrayList<>();
  20.     for (int i = 0; i < newsTypes.length; i++) {
  21.         NewsInfo newsInfo = new NewsInfo();
  22.         newsInfo.setTitle(newsTitles[i]);
  23.         newsInfo.setType(newsTypes[i]);
  24.         totalNews.add(newsInfo);
  25.     }
  26.     selectNews.addAll(totalNews);
  27.     newsListProvider = new NewsListProvider(selectNews, this);
  28.     newsListProvider.notifyDataChanged();
  29. }
复制代码
将Provider应用到ListContainer:

  1. private void  setListContainer() {
  2.     selectorListContainer.setItemProvider(newsTypeProvider);
  3.     newsListContainer.setItemProvider(newsListProvider);
  4. }
复制代码
为ListContainer绑定点击事件:
  1. private void initListener() {
  2.     selectorListContainer.setItemClickedListener((listContainer, component, position, listener) -> {
  3.         setCategorizationFocus(false);
  4.         Component newsTypeText = component.findComponentById(ResourceTable.Id_news_type_text);
  5.         if (newsTypeText instanceof Text) {
  6.             selectText = (Text) newsTypeText;
  7.         }
  8.         setCategorizationFocus(true);
  9.         selectNews.clear();
  10.         if (position == 0) {
  11.             selectNews.addAll(totalNews);
  12.         } else {
  13.             String newsType = selectText.getText();
  14.             for (NewsInfo newsData : totalNews) {
  15.                 if (newsType.equals(newsData.getType())) {
  16.                     selectNews.add(newsData);
  17.                 }
  18.             }
  19.         }
  20.         updateListView();
  21.     });
  22.     selectorListContainer.setSelected(true);
  23.     selectorListContainer.setSelectedItemIndex(0);
  24. }

  25. private void setCategorizationFocus(boolean isFocus) {
  26.     if (selectText == null) {
  27.         return;
  28.     }
  29.     if (isFocus) {
  30.         selectText.setTextColor(new Color(Color.getIntColor("#afaafa")));
  31.         selectText.setScaleX(FOCUS_TEXT_SIZE);
  32.         selectText.setScaleY(FOCUS_TEXT_SIZE);
  33.     } else {
  34.         selectText.setTextColor(new Color(Color.getIntColor("#999999")));
  35.         selectText.setScaleX(UNFOCUS_TEXT_SIZE);
  36.         selectText.setScaleY(UNFOCUS_TEXT_SIZE);
  37.     }
  38. }

  39. private void updateListView() {
  40.     newsListProvider.notifyDataChanged();
  41.     newsListContainer.invalidate();
  42.     newsListContainer.scrollToCenter(0);
  43. }
复制代码
运行程序点击Run> Run 'listcontainer'运行hap包,进入到程序主页,点击主页的ListContainer即可看到新闻列表页面,点击页面上方不同的新闻类型,新闻列表会随之变化,效果如下所示:
   
6. 体验RadioContainer组件        
RadioContainer是RadioButton的容器,在其包裹下的RadioButton保证只有一个被选项。RadioContainer组件的使用方法详见常用组件开发指导。在本章节,我们将利用RadioContainer组件编写一道单选题。                        
创建module
可参考3.1创建步骤,其中Application/Library name命名为RadioButton,Module Name命名为radiobutton,Layout Name命名为radio_container。
    编写布局文件在src/main/resources/base/layout目录下新建布局文件radio_container.xml。
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DirectionalLayout
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4.     ohos:height="match_parent"
  5.     ohos:width="match_parent"
  6.     ohos:alignment="horizontal_center"
  7.     ohos:orientation="vertical"
  8.     ohos:left_padding="32vp">
  9.     <Text
  10.         ohos:height="match_content"
  11.         ohos:width="match_parent"
  12.         ohos:top_margin="32vp"
  13.         ohos:text="Question:Which of the following options belong to fruit?"
  14.         ohos:text_size="20fp"
  15.         ohos:layout_alignment="left"
  16.         ohos:multiple_lines="true"/>
  17.     <DirectionalLayout
  18.         ohos:height="match_content"
  19.         ohos:width="match_parent"
  20.         ohos:orientation="horizontal"
  21.         ohos:top_margin="8vp">
  22.         <Text
  23.             ohos:height="match_content"
  24.             ohos:width="match_content"
  25.             ohos:text="Your Answer:"
  26.             ohos:text_size="20fp"/>
  27.         <Text
  28.             ohos:id="$+id:answer"
  29.             ohos:height="match_content"
  30.             ohos:width="match_content"
  31.             ohos:text_size="20fp"
  32.             ohos:left_margin="18vp"
  33.             ohos:text="[]"
  34.             ohos:text_color="#FF3333"/>
  35.     </DirectionalLayout>
  36.     <RadioContainer
  37.         ohos:id="$+id:radio_container"
  38.         ohos:height="match_content"
  39.         ohos:width="200vp"
  40.         ohos:layout_alignment="left"
  41.         ohos:orientation="vertical"
  42.         ohos:top_margin="16vp"
  43.         ohos:left_margin="4vp">
  44.         <RadioButton
  45.             ohos:id="$+id:radio_button_1"
  46.             ohos:height="40vp"
  47.             ohos:width="match_content"
  48.             ohos:text="A.Apple"
  49.             ohos:text_size="20fp"
  50.             ohos:text_color_on="#FF3333"/>
  51.         <RadioButton
  52.             ohos:id="$+id:radio_button_2"
  53.             ohos:height="40vp"
  54.             ohos:width="match_content"
  55.             ohos:text="B.Potato"
  56.             ohos:text_size="20fp"
  57.             ohos:text_color_on="#FF3333"/>
  58.         <RadioButton
  59.             ohos:id="$+id:radio_button_3"
  60.             ohos:height="40vp"
  61.             ohos:width="match_content"
  62.             ohos:text="C.Pumpkin"
  63.             ohos:text_size="20fp"
  64.             ohos:text_color_on="#FF3333"/>
  65.         <RadioButton
  66.             ohos:id="$+id:radio_button_4"
  67.             ohos:height="40vp"
  68.             ohos:width="match_content"
  69.             ohos:text="D.Vegetables"
  70.             ohos:text_size="20fp"
  71.             ohos:text_color_on="#FF3333"/>
  72.     </RadioContainer>
  73. </DirectionalLayout>
复制代码
编写AbilitySlice文件在src/main/java/com/huawei/codelab/slice目录下新建RadioContainerSlice.java文件,继承AbilitySlice。
加载布局:
  1. @Override
  2. public void onStart(Intent intent) {
  3.     super.onStart(intent);
  4.     super.setUIContent(ResourceTable.Layout_radio_container);
  5.     initComponent();
  6. }
  7. 通过以下方法,定义RadioButton的背景:

  8. private StateElement getStateElement() {
  9.     ShapeElement elementButtonOn = new ShapeElement();
  10.     elementButtonOn.setRgbColor(RgbPalette.RED);
  11.     elementButtonOn.setShape(ShapeElement.OVAL);

  12.     ShapeElement elementButtonOff = new ShapeElement();
  13.     elementButtonOff.setRgbColor(RgbPalette.DARK_GRAY);
  14.     elementButtonOff.setShape(ShapeElement.OVAL);

  15.     StateElement checkElement = new StateElement();
  16.     checkElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, elementButtonOn);
  17.     checkElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, elementButtonOff);
  18.     return checkElement;
  19. }
复制代码
初始化组件并设置响应RadioContainer状态改变的事件,显示单选结果:
  1. private void initComponent() {
  2.     Text answer = (Text) findComponentById(ResourceTable.Id_answer);
  3.     RadioContainer container = (RadioContainer)findComponentById(ResourceTable.Id_radio_container);
  4.     int count = container.getChildCount();
  5.     for (int i = 0; i < count; i++) {
  6.         ((RadioButton) container.getComponentAt(i)).setButtonElement(getStateElement());
  7.     }
  8.     container.setMarkChangedListener((radioContainer1, index) -> {
  9.         answer.setText(String.format("[%c]", (char)('A'+index)));
  10.     });
  11. }
复制代码
运行程序点击Run> Run 'radiocontainer'运行hap包,进入到程序主页,点击主页的RadioContainer即可看到单选题页面,点击不同的选项,单选结果将同步刷新。效果如下所示:
   
7. 体验Checkbox组件        
Checkbox可以实现选中和取消选中的功能。Checkbox组件的使用方法详见常用组件开发指导。在本章节,我们将利用Checkbox组件编写一道多选题。               
创建module
可参考3.1创建步骤,其中Application/Library name命名为Checkbox,Module Name命名为checkbox,Layout Name命名为checkbox。
    编写布局文件在src/main/resources/base/layout目录下新建布局文件checkbox.xml。
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DirectionalLayout
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4.     ohos:height="match_parent"
  5.     ohos:width="match_parent"
  6.     ohos:orientation="vertical"
  7.     ohos:left_padding="32vp">
  8.     <Text
  9.         ohos:height="match_content"
  10.         ohos:width="match_parent"
  11.         ohos:top_margin="32vp"
  12.         ohos:text="Question:Which of the following are fruits?"
  13.         ohos:text_size="20fp"
  14.         ohos:layout_alignment="left"
  15.         ohos:multiple_lines="true"/>
  16.     <DirectionalLayout
  17.         ohos:height="match_content"
  18.         ohos:width="match_parent"
  19.         ohos:orientation="horizontal"
  20.         ohos:top_margin="8vp">
  21.         <Text
  22.             ohos:height="match_content"
  23.             ohos:width="match_content"
  24.             ohos:text="Your Answer:"
  25.             ohos:text_size="20fp"/>
  26.         <Text
  27.             ohos:id="$+id:text_answer"
  28.             ohos:height="match_content"
  29.             ohos:width="match_content"
  30.             ohos:text_size="20fp"
  31.             ohos:left_margin="18vp"
  32.             ohos:text="[]"
  33.             ohos:text_color="#FF3333"/>
  34.     </DirectionalLayout>
  35.     <Checkbox
  36.         ohos:id="$+id:checkbox_1"
  37.         ohos:top_margin="20vp"
  38.         ohos:height="match_content"
  39.         ohos:width="match_content"
  40.         ohos:text="A Apples"
  41.         ohos:text_size="20fp"
  42.         ohos:text_color_on="#FF3333"
  43.         ohos:text_color_off="#000000"/>
  44.     <Checkbox
  45.         ohos:id="$+id:checkbox_2"
  46.         ohos:top_margin="20vp"
  47.         ohos:height="match_content"
  48.         ohos:width="match_content"
  49.         ohos:text="B Bananas"
  50.         ohos:text_size="20fp"
  51.         ohos:text_color_on="#FF3333"
  52.         ohos:text_color_off="#000000"/>
  53.     <Checkbox
  54.         ohos:id="$+id:checkbox_3"
  55.         ohos:top_margin="20vp"
  56.         ohos:height="match_content"
  57.         ohos:width="match_content"
  58.         ohos:text="C Strawberries"
  59.         ohos:text_size="20fp"
  60.         ohos:text_color_on="#FF3333"
  61.         ohos:text_color_off="#000000" />
  62.     <Checkbox
  63.         ohos:id="$+id:checkbox_4"
  64.         ohos:top_margin="20vp"
  65.         ohos:height="match_content"
  66.         ohos:width="match_content"
  67.         ohos:text="D Potatoes"
  68.         ohos:text_size="20fp"
  69.         ohos:text_color_on="#FF3333"
  70.         ohos:text_color_off="black" />
  71. </DirectionalLayout>
复制代码
编写AbilitySlice文件在src/main/java/com/huawei/codelab/slice目录下新建CheckboxSlice.java文件,继承AbilitySlice。
定义成员变量,加载布局:
  1. private Text answer;
  2. private Set<String> selectedSet = new HashSet<>();

  3. @Override
  4. public void onStart(Intent intent) {
  5.     super.onStart(intent);
  6.     super.setUIContent(ResourceTable.Layout_checkbox);
  7.     answer = (Text) findComponentById(ResourceTable.Id_text_answer);
  8.     initCheckbox();
  9. }
复制代码
通过以下方法设置Checkbox的背景:
  1. private StateElement getStateElement() {
  2.     ShapeElement elementButtonOn = new ShapeElement();
  3.     elementButtonOn.setRgbColor(RgbPalette.RED);
  4.     elementButtonOn.setShape(ShapeElement.OVAL);

  5.     ShapeElement elementButtonOff = new ShapeElement();
  6.     elementButtonOff.setRgbColor(RgbPalette.WHITE);
  7.     elementButtonOff.setShape(ShapeElement.OVAL);

  8.     StateElement checkElement = new StateElement();
  9.     checkElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, elementButtonOn);
  10.     checkElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, elementButtonOff);
  11.     return checkElement;
  12. }
复制代码
通过以下方法订阅Checkbox状态变化:
  1. private void setCheckedStateChangedListener(Checkbox checkbox, String CheckValue) {
  2.     checkbox.setCheckedStateChangedListener((view, state) -> {
  3.         if (state) {
  4.             selectedSet.add(CheckValue);
  5.         }else {
  6.             selectedSet.remove(CheckValue);
  7.         }
  8.         showAnswer();
  9.     });
  10. }

  11. private void showAnswer() {
  12.     String select = selectedSet.toString();
  13.     answer.setText(select);
  14. }
复制代码
初始化Checkbox并设置订阅事件:
  1. private void initCheckbox() {
  2.     Checkbox checkbox1 = (Checkbox) findComponentById(ResourceTable.Id_checkbox_1);
  3.     checkbox1.setButtonElement(getStateElement());
  4.     setCheckedStateChangedListener(checkbox1, "A");
  5.     if (checkbox1.isChecked()) {
  6.         selectedSet.add("A");
  7.     }

  8.     Checkbox checkbox2 = (Checkbox) findComponentById(ResourceTable.Id_checkbox_2);
  9.     checkbox2.setButtonElement(getStateElement());
  10.     setCheckedStateChangedListener(checkbox2, "B");
  11.     if (checkbox2.isChecked()) {
  12.         selectedSet.add("B");
  13.     }

  14.     Checkbox checkbox3 = (Checkbox) findComponentById(ResourceTable.Id_checkbox_3);
  15.     checkbox3.setButtonElement(getStateElement());
  16.     setCheckedStateChangedListener(checkbox3, "C");
  17.     if (checkbox3.isChecked()) {
  18.         selectedSet.add("C");
  19.     }

  20.     Checkbox checkbox4 = (Checkbox) findComponentById(ResourceTable.Id_checkbox_4);
  21.     checkbox4.setButtonElement(getStateElement());
  22.     setCheckedStateChangedListener(checkbox4, "D");
  23.     if (checkbox4.isChecked()) {
  24.         selectedSet.add("D");
  25.     }
  26. }
复制代码
运行程序
点击Run> Run 'checkbox'运行hap包,进入到程序主页,点击主页的Checkbox即可看到多选题页面,点击不同的选项,多选结果将同步刷新。效果如下所示:

   
8. 体验DatePicker组件        
DatePicker主要供用户选择日期。DatePicker组件的使用方法详见常用组件开发指导。在本章节,我们将利用DatePicker组件编写一个日期选择小程序。           
创建module
可参考3.1创建步骤,其中Application/Library name命名为DatePicker,Module Name命名为datepicker,Layout Name命名为data_picker。
        编写布局文件在src/main/resources/base/layout目录下新建布局文件data_picker.xml。
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DirectionalLayout
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4.     ohos:width="match_parent"
  5.     ohos:height="match_parent"
  6.     ohos:orientation="vertical">
  7.     <DatePicker
  8.         ohos:id="$+id:date_pick"
  9.         ohos:height="150vp"
  10.         ohos:width="300vp"
  11.         ohos:background_element="#EDEDED"
  12.         ohos:top_margin="13vp"
  13.         ohos:layout_alignment="horizontal_center"
  14.         ohos:selected_normal_text_margin_ratio="6"
  15.         ohos:selected_text_size="16vp"
  16.         ohos:selected_text_color="#0000FF"
  17.         ohos:operated_text_color="#0000FF"
  18.         ohos:normal_text_size="13vp"
  19.         ohos:top_line_element="#9370DB"
  20.         ohos:bottom_line_element="#9370DB"
  21.         ohos:shader_color="#00CED1">
  22.     </DatePicker>
  23.     <DirectionalLayout
  24.         ohos:width="match_content"
  25.         ohos:height="35vp"
  26.         ohos:top_margin="13vp"
  27.         ohos:layout_alignment="horizontal_center"
  28.         ohos:orientation="horizontal">
  29.         <Text
  30.             ohos:width="match_content"
  31.             ohos:height="match_parent"
  32.             ohos:text_size="15vp"
  33.             ohos:padding="4vp"
  34.             ohos:text="Currently selected date:  "/>
  35.         <Text
  36.             ohos:id="$+id:text_date"
  37.             ohos:height="match_content"
  38.             ohos:width="100vp"
  39.             ohos:background_element="$graphic:button_element"
  40.             ohos:hint="date"
  41.             ohos:left_margin="13vp"
  42.             ohos:padding="4vp"
  43.             ohos:text_size="15vp">
  44.         </Text>
  45.     </DirectionalLayout>
  46. </DirectionalLayout>
复制代码
编写AbilitySlice文件在src/main/java/com/huawei/codelab/slice目录下新建DatePickerSlice.java文件,继承AbilitySlice。
定义成员变量,加载布局:
  1. private DatePicker datePicker;
  2. private Text textDate;

  3. @Override
  4. public void onStart(Intent intent) {
  5.     super.onStart(intent);
  6.     super.setUIContent(ResourceTable.Layout_data_picker);
  7.     initComponent();
  8.     initDate();
  9.     setValueChangedListener();
  10. }
复制代码
初始化组件:
  1. private void initComponent() {
  2.     datePicker = (DatePicker) findComponentById(ResourceTable.Id_date_pick);
  3.     textDate = (Text) findComponentById(ResourceTable.Id_text_date);
  4. }
复制代码
显示初始日期:

  1. private void initDate() {
  2.     int day = datePicker.getDayOfMonth();
  3.     int month = datePicker.getMonth();
  4.     int year = datePicker.getYear();
  5.     textDate.setText(String.format("%02d/%02d/%4d", day, month, year));
  6. }
复制代码
为DatePicker设置订阅事件:
  1. private void setValueChangedListener(){
  2.     datePicker.setValueChangedListener(
  3.         new DatePicker.ValueChangedListener() {
  4.             @Override
  5.             public void onValueChanged(DatePicker picker, int year, int monthOfYear, int dayOfMonth) {
  6.                 textDate.setText(String.format("%02d/%02d/%4d", dayOfMonth, monthOfYear, year));
  7.             }
  8.         }
  9.     );
  10. }
复制代码
运行程序点击Run> Run 'datepicker'运行hap包,进入到程序主页,点击主页的DatePicker即可看到日期选择页面,默认显示当前日期;滑动年/月/日,下面显示的日期将同步刷新。效果如下所示:
   
9. 体验DirectionalLayout布局        
DirectionalLayout是Java UI中的一种重要组件布局,用于将一组组件(Component)按照水平或者垂直方向排布,能够方便地对齐布局内的组件。DirectionalLayout布局的使用方法详见常用布局开发指导。在此章节,我们将利用DirectionalLayout布局编写一个中秋灯谜列表。                  
创建module
可参考3.1创建步骤,其中Application/Library name命名为DirectionalLayout,Module Name命名为directionallayout,Layout Name命名为directional_layout。
    编写布局文件在src/main/resources/base/layout目录下新建布局文件directional_layout.xml。
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DirectionalLayout
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4.     ohos:width="match_parent"
  5.     ohos:height="match_parent"
  6.     ohos:top_margin="13fp"
  7.     ohos:orientation="vertical">
  8.     <Text
  9.         ohos:width="match_content"
  10.         ohos:height="match_content"
  11.         ohos:text="Lantern riddles of Mid Autumn Festival"
  12.         ohos:text_alignment="center"
  13.         ohos:multiple_lines="true"
  14.         ohos:layout_alignment="center"
  15.         ohos:top_margin="20vp"
  16.         ohos:text_size="23vp"/>
  17.     <Text
  18.         ohos:width="match_parent"
  19.         ohos:height="match_content"
  20.         ohos:text="1.what man cannot live in a house?"
  21.         ohos:multiple_lines="true"
  22.         ohos:left_margin="20vp"
  23.         ohos:top_margin="20vp"
  24.         ohos:text_size="18vp"/>
  25.     <Text
  26.         ohos:width="match_parent"
  27.         ohos:height="match_content"
  28.         ohos:text="2.What never asks questions but gets a lot of answers?"
  29.         ohos:multiple_lines="true"
  30.         ohos:left_margin="20vp"
  31.         ohos:top_margin="20vp"
  32.         ohos:text_size="18vp"/>
  33.     <Text
  34.         ohos:width="match_parent"
  35.         ohos:height="match_content"
  36.         ohos:text="3.A mouse has a large pocket.What is it?"
  37.         ohos:multiple_lines="true"
  38.         ohos:left_margin="20vp"
  39.         ohos:top_margin="20vp"
  40.         ohos:text_size="18vp"/>
  41.     <Text
  42.         ohos:width="match_parent"
  43.         ohos:height="match_content"
  44.         ohos:text="4.What can hear you without ears and can answer you without a mouth?"
  45.         ohos:multiple_lines="true"
  46.         ohos:left_margin="20vp"
  47.         ohos:top_margin="20vp"
  48.         ohos:text_size="18vp"/>
  49.     <Text
  50.         ohos:width="match_parent"
  51.         ohos:height="match_content"
  52.         ohos:text="5.What is higher without a head than with a head?"
  53.         ohos:multiple_lines="true"
  54.         ohos:left_margin="20vp"
  55.         ohos:top_margin="20vp"
  56.         ohos:text_size="18vp"/>
  57.     <Text
  58.         ohos:width="match_parent"
  59.         ohos:height="match_content"
  60.         ohos:text="6.What is dark but made by light?"
  61.         ohos:multiple_lines="true"
  62.         ohos:left_margin="20vp"
  63.         ohos:top_margin="20vp"
  64.         ohos:text_size="18vp"/>
  65.     <Text
  66.         ohos:width="match_parent"
  67.         ohos:height="match_content"
  68.         ohos:text="7.What person tried to make you smile most of the time?"
  69.         ohos:multiple_lines="true"
  70.         ohos:left_margin="20vp"
  71.         ohos:top_margin="20vp"
  72.         ohos:text_size="18vp"/>
  73.     <Text
  74.         ohos:width="match_parent"
  75.         ohos:height="match_content"
  76.         ohos:text="8.You have it.You read it.There're some pictures in it?"
  77.         ohos:multiple_lines="true"
  78.         ohos:left_margin="20vp"
  79.         ohos:top_margin="20vp"
  80.         ohos:text_size="18vp"/>
  81.     <Text
  82.         ohos:width="match_parent"
  83.         ohos:height="match_content"
  84.         ohos:text="9.What animal has a head like a cat, eyes like a cat, a tail like a cat, but isn't a cat? "
  85.         ohos:multiple_lines="true"
  86.         ohos:left_margin="20vp"
  87.         ohos:top_margin="20vp"
  88.         ohos:text_size="18vp"/>
  89.     <Text
  90.         ohos:width="match_parent"
  91.         ohos:height="match_content"
  92.         ohos:text="10.What has hands but no feet, a face but no eyes, tells but not talk?"
  93.         ohos:multiple_lines="true"
  94.         ohos:left_margin="20vp"
  95.         ohos:top_margin="20vp"
  96.         ohos:text_size="18vp"/>
  97. </DirectionalLayout>
复制代码
编写AbilitySlice文件在src/main/java/com/huawei/codelab/slice目录下新建DirectionalLayoutSlice.java文件,继承AbilitySlice。
加载布局:
  1. @Override
  2. public void onStart(Intent intent) {
  3.     super.onStart(intent);
  4.     super.setUIContent(ResourceTable.Layout_directional_layout);
  5. }
复制代码

运行程序点击Run> Run 'directionallayout'运行hap包,进入到程序主页,点击主页的DirectionalLayout即可看到中秋灯谜页面。效果如下所示:

   
10. 体验DependentLayout布局        
DependentLayout是Java UI系统里的一种常见布局。与DirectionalLayout相比,拥有更多的排布方式,每个组件可以指定相对于其他同级元素的位置,或者指定相对于父组件的位置。DependentLayout布局的使用方法可详见常用布局开发指导。在本章节,我们将利用DirectionalLayout和DependentLayout布局编写一个新闻详情页面。                     
创建module
可参考3.1创建步骤,其中Application/Library name命名为DependentLayout,Module Name命名为dependentlayout,Layout Name命名为dependent_layout。
        编写布局文件在src/main/resources/base/layout目录下新建布局文件dependent_layout.xml。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DependentLayout
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4.     ohos:id="$+id:parent_layout"
  5.     ohos:height="match_parent"
  6.     ohos:width="match_parent">
  7.     <ScrollView
  8.         ohos:height="match_parent"
  9.         ohos:width="match_parent">
  10.         <DirectionalLayout
  11.             ohos:height="match_content"
  12.             ohos:width="match_parent"
  13.             ohos:bottom_padding="70vp"
  14.             ohos:orientation="vertical">
  15.             <DirectionalLayout
  16.                 ohos:height="match_content"
  17.                 ohos:width="match_parent"
  18.                 ohos:alignment="vertical_center"
  19.                 ohos:orientation="horizontal"
  20.                 ohos:background_element="#FFFFFF">
  21.                 <Text
  22.                     ohos:id="$+id:title_icon"
  23.                     ohos:height="match_content"
  24.                     ohos:width="match_content"
  25.                     ohos:text="NewsDemo"
  26.                     ohos:left_margin="20vp"
  27.                     ohos:text_size="20fp"
  28.                     ohos:weight="1"/>
  29.                 <Text
  30.                     ohos:id="$+id:read_num"
  31.                     ohos:height="match_content"
  32.                     ohos:width="match_content"
  33.                     ohos:right_margin="10vp"
  34.                     ohos:text="reads:10"
  35.                     ohos:text_size="10fp"/>
  36.                 <Text
  37.                     ohos:id="$+id:likes_num"
  38.                     ohos:height="match_content"
  39.                     ohos:width="match_content"
  40.                     ohos:right_margin="20vp"
  41.                     ohos:text="likes:9"
  42.                     ohos:text_size="10fp"/>
  43.             </DirectionalLayout>
  44.             <Text
  45.                 ohos:id="$+id:title_text"
  46.                 ohos:height="match_content"
  47.                 ohos:width="match_parent"
  48.                 ohos:left_margin="20vp"
  49.                 ohos:max_text_lines="4"
  50.                 ohos:multiple_lines="true"
  51.                 ohos:right_margin="20vp"
  52.                 ohos:text="Ten Future Trends of Digital Energy"
  53.                 ohos:text_color="#000000"
  54.                 ohos:text_size="18fp"
  55.                 ohos:top_margin="10vp"/>
  56.             <Text
  57.                 ohos:id="$+id:title_content"
  58.                 ohos:height="match_content"
  59.                 ohos:width="match_parent"
  60.                 ohos:left_margin="20vp"
  61.                 ohos:multiple_lines="true"
  62.                 ohos:right_margin="20vp"
  63.                 ohos:text="Energy digitalization is an inevitable trend. Innovative integration of digital and energy technologies enables end-to-end visual, manageable, and controllable intelligent management of energy infrastructure, improving energy efficiency."
  64.                 ohos:text_alignment="center_horizontal"
  65.                 ohos:text_color="#708090"
  66.                 ohos:text_size="16fp"
  67.                 ohos:top_margin="5vp"/>
  68.             <DirectionalLayout
  69.                 ohos:height="match_content"
  70.                 ohos:width="match_parent"
  71.                 ohos:orientation="horizontal">
  72.                 <Image
  73.                     ohos:id="$+id:image_content1"
  74.                     ohos:height="100vp"
  75.                     ohos:width="0vp"
  76.                     ohos:image_src="$media:news_image_left"
  77.                     ohos:layout_alignment="center"
  78.                     ohos:left_margin="20vp"
  79.                     ohos:right_margin="2vp"
  80.                     ohos:top_margin="10vp"
  81.                     ohos:weight="1"/>
  82.                 <Image
  83.                     ohos:id="$+id:image_content2"
  84.                     ohos:height="100vp"
  85.                     ohos:width="0vp"
  86.                     ohos:image_src="$media:news_image"
  87.                     ohos:layout_alignment="center"
  88.                     ohos:left_margin="10vp"
  89.                     ohos:right_margin="2vp"
  90.                     ohos:top_margin="10vp"
  91.                     ohos:weight="1"/>
  92.                 <Image
  93.                     ohos:id="$+id:image_content3"
  94.                     ohos:height="100vp"
  95.                     ohos:width="0vp"
  96.                     ohos:image_src="$media:news_image_right"
  97.                     ohos:layout_alignment="center"
  98.                     ohos:left_margin="2vp"
  99.                     ohos:right_margin="20vp"
  100.                     ohos:top_margin="10vp"
  101.                     ohos:weight="1"/>
  102.             </DirectionalLayout>
  103.         </DirectionalLayout>
  104.     </ScrollView>
  105.     <Component
  106.         ohos:height="0.5vp"
  107.         ohos:width="match_parent"
  108.         ohos:above="$+id:bottom_layout"
  109.         ohos:background_element="#EAEAEC"/>
  110.     <DirectionalLayout
  111.         ohos:id="$+id:bottom_layout"
  112.         ohos:height="50vp"
  113.         ohos:width="match_parent"
  114.         ohos:align_parent_bottom="true"
  115.         ohos:alignment="vertical_center"
  116.         ohos:background_element="#ffffff"
  117.         ohos:left_padding="20vp"
  118.         ohos:orientation="horizontal"
  119.         ohos:right_padding="20vp">
  120.         <TextField
  121.             ohos:height="30vp"
  122.             ohos:width="160vp"
  123.             ohos:background_element="$graphic:corner_bg_comment"
  124.             ohos:hint="Enter a comment."
  125.             ohos:left_padding="5vp"
  126.             ohos:right_padding="10vp"
  127.             ohos:text_alignment="vertical_center"
  128.             ohos:text_size="15vp"/>
  129.         <Image
  130.             ohos:height="20vp"
  131.             ohos:width="20vp"
  132.             ohos:scale_mode="stretch"
  133.             ohos:image_src="$media:message_icon"
  134.             ohos:left_margin="20vp"/>
  135.         <Image
  136.             ohos:height="20vp"
  137.             ohos:width="20vp"
  138.             ohos:scale_mode="stretch"
  139.             ohos:image_src="$media:collect_icon"
  140.             ohos:left_margin="20vp"/>
  141.         <Image
  142.             ohos:height="20vp"
  143.             ohos:width="20vp"
  144.             ohos:scale_mode="stretch"
  145.             ohos:image_src="$media:like_icon"
  146.             ohos:left_margin="20vp"/>
  147.         <Image
  148.             ohos:height="20vp"
  149.             ohos:width="20vp"
  150.             ohos:scale_mode="stretch"
  151.             ohos:image_src="$media:share_icon"
  152.             ohos:left_margin="20vp"/>
  153.     </DirectionalLayout>
  154. </DependentLayout>
复制代码
编写AbilitySlice文件在src/main/java/com/huawei/codelab/slice目录下新建DependentLayoutSlice.java文件,继承AbilitySlice。
加载布局:
  1. @Override
  2. public void onStart(Intent intent) {
  3.     super.onStart(intent);
  4.     super.setUIContent(ResourceTable.Layout_dependent_layout);
  5. }
复制代码
运行程序点击Run> Run 'dependentlayout'运行hap包,进入到程序主页,点击主页的DependentLayout即可看到新闻详情页面,效果如下所示:

   
11. 体验StackLayout布局        
StackLayout直接在屏幕上开辟出一块空白的区域,添加到这个布局中的视图都是以层叠的方式显示,而它会把这些视图默认放到这块区域的左上角,第一个添加到布局中的视图显示在最底层,最后一个被放在最顶层。上一层的视图会覆盖下一层的视图。StackLayout布局的使用方法详见常用布局开发指导。
创建module
可参考3.1创建步骤,其中Application/Library name命名为StackLayout,Module Name命名为stacklayout,Layout Name命名为stack_layout。
         编写布局文件在src/main/resources/base/layout目录下新建布局文件stack_layout.xml。
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <StackLayout
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4.     ohos:id="$+id:stack_layout"
  5.     ohos:height="match_parent"
  6.     ohos:width="match_parent">
  7.     <Text
  8.         ohos:id="$+id:text_blue"
  9.         ohos:text_alignment="bottom|horizontal_center"
  10.         ohos:text_size="24fp"
  11.         ohos:text="Layer1"
  12.         ohos:height="400vp"
  13.         ohos:width="match_parent"
  14.         ohos:background_element="#70dbdb" />
  15.     <Text
  16.         ohos:id="$+id:text_light_purple"
  17.         ohos:text_alignment="bottom|horizontal_center"
  18.         ohos:text_size="24fp"
  19.         ohos:text="Layer2"
  20.         ohos:height="300vp"
  21.         ohos:width="300vp"
  22.         ohos:background_element="#EED2EE" />
  23.     <Text
  24.         ohos:id="$+id:text_green"
  25.         ohos:text_alignment="center"
  26.         ohos:text_size="24fp"
  27.         ohos:text="Layer3"
  28.         ohos:height="200vp"
  29.         ohos:width="200vp"
  30.         ohos:background_element="#B4EEB4" />
  31. </StackLayout>
复制代码
编写AbilitySlice文件在src/main/java/com/huawei/codelab/slice目录下新建StackLayoutSlice.java文件,继承AbilitySlice。
加载布局:
  1. @Override
  2. public void onStart(Intent intent) {
  3.     super.onStart(intent);
  4.     super.setUIContent(ResourceTable.Layout_stack_layout);
  5. }
复制代码
运行程序点击Run> Run 'stacklayout'运行hap包,进入到程序主页,点击主页的StackLayout即可看到页面效果如下:

   
12. 体验TableLayout布局        
TableLayout使用表格的方式划分子组件。TableLayout布局的使用方法详见常用组件开发指导。在本章节,我们将利用TableLayout布局编写一个拨号盘。        
创建module
可参考3.1创建步骤,其中Application/Library name命名为TableLayout,Module Name命名为tablelayout,Layout Name命名为table_layout。
     编写布局文件在src/main/resources/base/layout目录下新建布局文件table_layout.xml。
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DirectionalLayout
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4.     ohos:width="match_parent"
  5.     ohos:height="match_parent"
  6.     ohos:background_element="#EDEDED"
  7.     ohos:layout_alignment="center"
  8.     ohos:orientation="vertical">
  9.     <Text
  10.         ohos:id="$+id:info"
  11.         ohos:width="match_content"
  12.         ohos:height="30vp"
  13.         ohos:text_size="20fp"
  14.         ohos:top_margin="20vp"
  15.         ohos:text=""
  16.         ohos:text_alignment="center"
  17.         ohos:layout_alignment="horizontal_center"/>
  18.     <TableLayout
  19.         ohos:id="$+id:table"
  20.         ohos:width="700"
  21.         ohos:height="match_content"
  22.         ohos:orientation="horizontal"
  23.         ohos:layout_alignment="horizontal_center"
  24.         ohos:top_margin="10"
  25.         ohos:column_count="3">
  26.         <Button
  27.             ohos:width="50vp"
  28.             ohos:height="50vp"
  29.             ohos:text_size="15fp"
  30.             ohos:left_margin="20vp"
  31.             ohos:top_margin="15vp"
  32.             ohos:background_element="$graphic:circle_button_element"
  33.             ohos:text="1"
  34.             ohos:text_alignment="center"/>
  35.         <Button
  36.             ohos:width="50vp"
  37.             ohos:height="50vp"
  38.             ohos:text_size="15fp"
  39.             ohos:left_margin="20vp"
  40.             ohos:top_margin="15vp"
  41.             ohos:background_element="$graphic:circle_button_element"
  42.             ohos:text="2"
  43.             ohos:text_alignment="center"/>
  44.         <Button
  45.             ohos:width="50vp"
  46.             ohos:height="50vp"
  47.             ohos:text_size="15fp"
  48.             ohos:left_margin="20vp"
  49.             ohos:top_margin="15vp"
  50.             ohos:background_element="$graphic:circle_button_element"
  51.             ohos:text="3"
  52.             ohos:text_alignment="center"/>
  53.         <Button
  54.             ohos:width="50vp"
  55.             ohos:height="50vp"
  56.             ohos:text_size="15fp"
  57.             ohos:left_margin="20vp"
  58.             ohos:top_margin="15vp"
  59.             ohos:background_element="$graphic:circle_button_element"
  60.             ohos:text="4"
  61.             ohos:text_alignment="center"/>
  62.         <Button
  63.             ohos:width="50vp"
  64.             ohos:height="50vp"
  65.             ohos:text_size="15fp"
  66.             ohos:left_margin="20vp"
  67.             ohos:top_margin="15vp"
  68.             ohos:background_element="$graphic:circle_button_element"
  69.             ohos:text="5"
  70.             ohos:text_alignment="center"/>
  71.         <Button
  72.             ohos:width="50vp"
  73.             ohos:height="50vp"
  74.             ohos:text_size="15fp"
  75.             ohos:left_margin="20vp"
  76.             ohos:top_margin="15vp"
  77.             ohos:background_element="$graphic:circle_button_element"
  78.             ohos:text="6"
  79.             ohos:text_alignment="center"/>
  80.         <Button
  81.             ohos:width="50vp"
  82.             ohos:height="50vp"
  83.             ohos:text_size="15fp"
  84.             ohos:left_margin="20vp"
  85.             ohos:top_margin="15vp"
  86.             ohos:background_element="$graphic:circle_button_element"
  87.             ohos:text="7"
  88.             ohos:text_alignment="center"/>
  89.         <Button
  90.             ohos:width="50vp"
  91.             ohos:height="50vp"
  92.             ohos:text_size="15fp"
  93.             ohos:left_margin="20vp"
  94.             ohos:top_margin="15vp"
  95.             ohos:background_element="$graphic:circle_button_element"
  96.             ohos:text="8"
  97.             ohos:text_alignment="center"/>
  98.         <Button
  99.             ohos:width="50vp"
  100.             ohos:height="50vp"
  101.             ohos:text_size="15fp"
  102.             ohos:left_margin="20vp"
  103.             ohos:top_margin="15vp"
  104.             ohos:background_element="$graphic:circle_button_element"
  105.             ohos:text="9"
  106.             ohos:text_alignment="center"/>
  107.         <Button
  108.             ohos:width="50vp"
  109.             ohos:height="50vp"
  110.             ohos:text_size="15fp"
  111.             ohos:left_margin="20vp"
  112.             ohos:top_margin="15vp"
  113.             ohos:background_element="$graphic:circle_button_element"
  114.             ohos:text="*"
  115.             ohos:text_alignment="center"/>
  116.         <Button
  117.             ohos:width="50vp"
  118.             ohos:height="50vp"
  119.             ohos:text_size="15fp"
  120.             ohos:left_margin="20vp"
  121.             ohos:top_margin="15vp"
  122.             ohos:background_element="$graphic:circle_button_element"
  123.             ohos:text="0"
  124.             ohos:text_alignment="center"/>
  125.         <Button
  126.             ohos:width="50vp"
  127.             ohos:height="50vp"
  128.             ohos:text_size="15fp"
  129.             ohos:left_margin="20vp"
  130.             ohos:top_margin="15vp"
  131.             ohos:background_element="$graphic:circle_button_element"
  132.             ohos:text="#"
  133.             ohos:text_alignment="center"/>
  134.     </TableLayout>
  135.     <DirectionalLayout
  136.         ohos:width="match_content"
  137.         ohos:height="match_content"
  138.         ohos:top_margin="20vp"
  139.         ohos:layout_alignment="horizontal_center"
  140.         ohos:orientation="horizontal">
  141.         <Button
  142.             ohos:id="$+id:call"
  143.             ohos:width="60vp"
  144.             ohos:height="35vp"
  145.             ohos:text_size="15fp"
  146.             ohos:text="CALL"
  147.             ohos:background_element="$graphic:button_element"
  148.             ohos:text_alignment="center"/>
  149.         <Button
  150.             ohos:id="$+id:clear"
  151.             ohos:width="60vp"
  152.             ohos:height="35vp"
  153.             ohos:text_size="15fp"
  154.             ohos:text="CLEAR"
  155.             ohos:background_element="$graphic:button_element"
  156.             ohos:left_margin="10vp"
  157.             ohos:text_alignment="center"/>
  158.     </DirectionalLayout>
  159. </DirectionalLayout>
复制代码
编写AbilitySlice文件在src/main/java/com/huawei/codelab/slice目录下新建TableLayoutSlice.java文件,继承AbilitySlice。
定义成员变量,加载布局:
  1. private Text info;
  2. private Button call;
  3. private Button clear;

  4. @Override
  5. public void onStart(Intent intent) {
  6.     super.onStart(intent);
  7.     super.setUIContent(ResourceTable.Layout_table_layout);
  8.     initComponent();
  9.     setClickedListener();
  10. }
复制代码
初始化组件:
  1. private void initComponent() {
  2.     info = (Text)findComponentById(ResourceTable.Id_info);
  3.     call = (Button)findComponentById(ResourceTable.Id_call);
  4.     clear = (Button)findComponentById(ResourceTable.Id_clear);
  5. }
复制代码
设置点击事件:
  1. private void setClickedListener() {
  2.     call.setClickedListener(new Component.ClickedListener() {
  3.         @Override
  4.         public void onClick(Component component) {
  5.             String toastInfo = info.getText();
  6.             if (toastInfo == null || toastInfo.isEmpty()) {
  7.                 toastInfo = "Please enter the number!";
  8.             } else {
  9.                 toastInfo = "Call " + info.getText();
  10.             }
  11.             new ToastDialog(getContext())
  12.                     .setText(toastInfo)
  13.                     .setAlignment(LayoutAlignment.CENTER)
  14.                     .setOffset(0,180)
  15.                     .show();
  16.         }
  17.     });

  18.     clear.setClickedListener(new Component.ClickedListener() {
  19.         @Override
  20.         public void onClick(Component component) {
  21.             info.setText("");
  22.         }
  23.     });

  24.     TableLayout table = (TableLayout)findComponentById(ResourceTable.Id_table);
  25.     int childNum = table.getChildCount();
  26.     for (int index = 0; index < childNum; index++) {
  27.         Button child = (Button)(table.getComponentAt(index));
  28.         child.setClickedListener(new Component.ClickedListener() {
  29.             @Override
  30.             public void onClick(Component component) {
  31.                 if (component instanceof Button) {
  32.                     Button button = (Button)component;
  33.                     info.setText(info.getText() + button.getText());
  34.                 }
  35.             }
  36.         });
  37.     }
  38. }
复制代码
运行程序点击Run> Run 'tablelayout'运行hap包,进入到程序主页,点击主页的TableLayout即可看到拨号盘页面。点击拨号盘上的按钮,拨号盘上方会显示输入的号码;点击拨号盘下方的CLEAR按钮,拨号盘上方显示内容将清空。效果如下所示:
点击下方的CALL按钮,将弹出ToastDialog,效果如下所示:
说明
此篇Codelab中的所有代码仅供demo演示参考使用。


回帖

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容图片侵权或者其他问题,请联系本站作侵删。 侵权投诉
链接复制成功,分享给好友