1. 程式人生 > 其它 >鴻蒙OS應用開發之——Java UI框架-常用元件TabList和Tab

鴻蒙OS應用開發之——Java UI框架-常用元件TabList和Tab

技術標籤:HarmonyOS鴻蒙

一 概念

  • Tab為某個頁籤
  • TabList為包含Tab的頁籤欄,可以實現多個頁籤的切換

二 建立TabList

3.1 XML中建立TabList

<?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">

    <TabList
        ohos:id="$+id:tab_list"
        ohos:top_margin="10vp"
        ohos:tab_margin="24vp"
        ohos:tab_length="140vp"
        ohos:text_size="20fp"
        ohos:height="36vp"
        ohos:width="match_parent"
        ohos:layout_alignment="center"
        ohos:orientation="horizontal"
        ohos:text_alignment="center"
        ohos:normal_text_color="#999999"
        ohos:selected_text_color="#FF0000"
        ohos:selected_tab_indicator_color="#FF0000"
        ohos:selected_tab_indicator_height="2vp"/>

</DirectionalLayout>

3.2 程式碼中新增Tab

 TabList tabList = (TabList) findComponentById(ResourceTable.Id_tab_list);

  TabList.Tab tab = tabList.new Tab(getContext());
  tab.setText("Image");
  tabList.addTab(tab);

  TabList.Tab tab2 = tabList.new Tab(getContext());
  tab2.setText("Video");
  tabList.addTab(tab2);

  TabList.Tab tab3 = tabList.new Tab(getContext());
  tab3.setText("Audio");
  tabList.addTab(tab3);

  TabList.Tab tab4 = tabList.new Tab(getContext());
  tab4.setText("HuaWei Share");
  tabList.addTab(tab4);

  tabList.setFixedMode(true);
  tabList.selectTab(tab);

3.3 響應焦點變化

tabList.addTabSelectedListener(new TabList.TabSelectedListener() {
   @Override
   public void onSelected(TabList.Tab tab) {
          // 當某個Tab從未選中狀態變為選中狀態時的回撥
          new ToastDialog(getContext()).setText("onSelected").show();
     }
     @Override
     public void onUnselected(TabList.Tab tab) {
         // 當某個Tab從選中狀態變為未選中狀態時的回撥
           new ToastDialog(getContext()).setText("onUnselected").show();

      }
     @Override
     public void onReselected(TabList.Tab tab) {
          // 當某個Tab已處於選中狀態,再次被點選時的狀態回撥
          new ToastDialog(getContext()).setText("onReselected").show();
       }
  });