1、Tablist

Tablist是harmonyOS的一个组件,它可以实现多个页签栏的切换,Tab为某个值页签。页签中可以放按钮、输入框等常见的组件,每个页签的布局可以不一致,可以设置成DirectionalLayout、TableLayout、AdaptiveBoxLayout等布局。每个Tab放置在Tablist中,每个页签的名称可以根据自己需要去设置,但应该简洁明了。

Tablist的共有属性继承ScrollView,属性如下图所示,如果想了解更多属性可参考HarmonyOS官方文档

PageSlider_华为


2、PageSlider

PageSlider是用于页面之间切换的组件,它通过响应滑动事件完成页面间的切换。

PageSlider无自有的XML属性,共有XML属性继承自:StackLayout

3、代码

测试程序共三个xml文件,ability_main.xml中包含Tablist和PageSlider,是主要布局文件,firstpage_tab.xml和message_tab.xml文件是两个tab,用于展示不同内容

PageSlider_华为_02


具体xml代码如下:

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:orientation="vertical"
    >
    <TabList
        ohos:id="$+id:tablist"
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:background_element="#dddddd"
        ohos:normal_text_color="#a0a0a0"
        ohos:selected_text_color="#0000FF"
        ohos:selected_tab_indicator_color="#00FF00"
        ohos:weight="1"
        />
    <PageSlider
        ohos:id="$+id:page_slider"
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:weight="9"
        >
    </PageSlider>

</DirectionalLayout>

firstpage_tab.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:orientation="vertical"
    >
    <Text
        ohos:id="$+id:testtext"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="这是首页"
        ohos:text_size="32fp"
        />
    <Button
        ohos:id="$+id:firstBt"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text_size="32fp"
        ohos:background_element="#0000f1"
        ohos:text="first"/>
</DirectionalLayout>

message_tab.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:orientation="vertical"
    ohos:background_element="#D8D536"
    >
    <Text
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="这是信息页"
        ohos:text_size="24fp"
        />
    <Button
        ohos:id="$+id:msgBt"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text_size="24fp"
        ohos:background_element="#0000ff"
        ohos:text="message"/>
</DirectionalLayout>

java代码

请忽略我代码中注释的代码,懒得去整理(狗头),TabPageSliderProvider主要是管理PageSlider。在程序中最重要的部分就是两个tab中为按钮添加监听事件,这个是我写这篇文章的主要目的!!!!!!之前为了实现两个tab中按钮的点击事件找了很多资料,也在官方文档中找了半天,最后啥也没有。

应为不同Tab是动态切换的,而两个tab中的资源又不共享,所以只能动态的添加按钮,一定不能将按钮在onStart时候加载进来!!!

PageSlider_华为_03


java工程结构

PageSlider_PageSlider_04


MainAbilitySlice.java

package com.example.tablistdemo2.slice;

import com.example.tablistdemo2.ResourceTable;
import com.example.tablistdemo2.provider.TabPageSliderProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.text.Layout;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * tablist + pageslider控件测试工程
 *  pageslider是用于两个tab之间切换时有动画效果
 * 时间:2022年10月12日
 * @auther ZX
 */



public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00201, "标签页");

    private TabList tabList;
    private TabList.Tab firstPageTab;//首页
    private TabList.Tab messageTab;//消息页

    private Component firstPageTableLayout;//首页页签界面布局
    private Component messagePageTableLayout;//信息页页签界面布局

//    private DirectionalLayout directionalLayout;//内容页,用于显示焦点页
    PageSlider pageSlider;//界面显示容器

    private Button firstBt;//首页按钮
    private Button msgBt;//信息页按钮
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initComponent();
        initPageSlider();
        initListener();
    }
    private void initComponent() {
        tabList = (TabList) findComponentById(ResourceTable.Id_tablist);
        firstPageTableLayout = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_firstpage_tab,null,false);
        messagePageTableLayout = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_message_tab,null,false);
//        directionalLayout = (DirectionalLayout)findComponentById(ResourceTable.Id_container_tab);


        pageSlider = (PageSlider) findComponentById(ResourceTable.Id_page_slider);

        //设置页签宽度为自适应,平均分配(适用于页签较少的情况)
        tabList.setFixedMode(true);//如果是false则表示固定宽度,true表示平均宽度


        firstPageTab = tabList.new Tab(getContext());
        firstPageTab.setText("first pg");//设置页签名称
        tabList.addTab(firstPageTab, true);//设置当前页为默认tab
//        directionalLayout.addComponent(firstPageTableLayout);

        messageTab = tabList.new Tab(getContext());
        messageTab.setText("msg pg");//设置页签名称
        tabList.addTab(messageTab);
    }
    //初始化pageslider
    private void initPageSlider() {
        List<Integer> layoutIds = new ArrayList<>();
        layoutIds.add(ResourceTable.Layout_firstpage_tab);
        layoutIds.add(ResourceTable.Layout_message_tab);
        pageSlider.setProvider(new TabPageSliderProvider(layoutIds,this));

        //tablist 与pageslider联动(当点击页签栏名称的时候页签内容跟着变化)
        tabList.addTabSelectedListener(new TabList.TabSelectedListener() {
            @Override
            public void onSelected(TabList.Tab tab) {
                //获取点击tab的索引
                int index = tab.getPosition();
                pageSlider.setCurrentPage(index);//设置pageslider的索引与tablist索引一致
                if(index == 0){//当前是首页

                }
                else{

                }
            }
            @Override
            public void onUnselected(TabList.Tab tab) {}
            @Override
            public void onReselected(TabList.Tab tab) {}
        });
        //pageslider 与tablist 联动(当滑动页签的时候标签栏名称跟着改变,与上边是相反的)
        pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {}
            @Override
            public void onPageSlideStateChanged(int i) {}
            @Override
            public void onPageChosen(int i) {
                //i 表示slider的索引
                if(tabList.getSelectedTabIndex() != i){//标签页与slider显示不一致
                    tabList.selectTabAt(i);
                }
            }
        });
    }
    /**
     * 初始化监听事件
     */
    private void initListener() {
        HiLog.info(label,"添加tab切换监听事件");
        tabList.addTabSelectedListener(new TabList.TabSelectedListener() {
            @Override
            public void onSelected(TabList.Tab tab) {
                HiLog.info(label,"onSelected tab.getPosition():"+tab.getPosition());
                if(tab.getPosition() == 0){
//                    directionalLayout.removeAllComponents();
//                    directionalLayout.addComponent(firstPageTableLayout);
                    initFirstListener();
                }
                else{
                    initMsgListener();
//                    directionalLayout.removeAllComponents();
//                    directionalLayout.addComponent(messagePageTableLayout );
                }
            }
            @Override
            public void onUnselected(TabList.Tab tab) {
                HiLog.info(label,"onUnselected tab.getPosition():"+tab.getPosition());
                if(tab.getPosition() == 0){
//                    directionalLayout.removeComponent(firstPageTableLayout);
                }
                else{
//                    directionalLayout.removeComponent(messagePageTableLayout);
                }
            }

            @Override
            public void onReselected(TabList.Tab tab) {
                HiLog.info(label,"onReselected onUnselected tab.getPosition():"+tab.getPosition());
            }
        });
        /**
         * 绑定首页按钮监听事件,注:如果是firstpagetab设置为默认tab时调用
         * initFirstListener(),如果messageTab设置为默认tab时调用initMsgListener()
         */
        initFirstListener();
    }
    //初始化首页tab中的按钮监听事件
    private void initFirstListener() {
        HiLog.info(label,"添加首页中按钮的监听事件");
        try {
            firstBt = (Button) findComponentById(ResourceTable.Id_firstBt);
            firstBt.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    new ToastDialog(getContext()).setText("这是首页").setAlignment(LayoutAlignment.CENTER).show();
                    HiLog.info(label,"点击了首页按钮");
                }
            });
        }
        catch (Exception e){
            HiLog.info(label,"出错信息:"+e.getMessage());
        }
    }
    //初始化消息tab中按钮监听事件
    private void initMsgListener(){
        HiLog.info(label,"添加消息中按钮的监听事件");
        msgBt = (Button) findComponentById(ResourceTable.Id_msgBt);
        msgBt.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                new ToastDialog(getContext()).setText("这是消息页").setAlignment(LayoutAlignment.CENTER).show();
                HiLog.info(label,"单击了消息页按钮");
            }
        });
    }
    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}

TabPageSliderProvider.java

package com.example.tablistdemo2.provider;

import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.PageSliderProvider;

import java.util.List;

public class TabPageSliderProvider extends PageSliderProvider {
    private List<Integer> layoutFilesIds;//存放布局文件的ID值
    private AbilitySlice abilitySlice;
    public TabPageSliderProvider(List<Integer> files, AbilitySlice abilitySlice){
        layoutFilesIds = files;
        this.abilitySlice =abilitySlice;
    }
    @Override
    public int getCount() {
        return layoutFilesIds.size();
    }
    //创建布局文件
    @Override
    public Object createPageInContainer(ComponentContainer componentContainer, int i) {
        Integer id = layoutFilesIds.get(i);
        Component component = LayoutScatter.getInstance(abilitySlice).parse(id,null,false);
        componentContainer.addComponent(component);
        return component;
    }
    //销毁对象
    @Override
    public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
        componentContainer.removeComponent((Component) o);
    }

    @Override
    public boolean isPageMatchToObject(Component component, Object o) {
        return false;
    }
}

运行效果

PageSlider_PageSlider_05


PageSlider_ide_06




如有侵权,请联系作者删除!!