一、Slice布局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"
ohos:background_element="black"
>
<TabList
ohos:id="$+id:tabList"
ohos:height="70vp"
ohos:width="match_parent"
ohos:orientation="horizontal"
ohos:text_alignment="center"
ohos:text_size="20fp"
ohos:normal_text_color="#999999"
ohos:selected_text_color="#999999"
ohos:selected_tab_indicator_color="#FFFFFF"
ohos:selected_tab_indicator_height="2vp"
/>
<StackLayout
ohos:id="$+id:stack_layout"
ohos:height="match_parent"
ohos:width="match_parent"/>
</DirectionalLayout>
二、初始化组件
mTabList = (TabList) findComponentById(ResourceTable.Id_tabList);
三、为tabList配置tab
private void initTabs() {
// 设置TabList的属性与页签项中字体的大小
mTabList.setCentralScrollMode(true);
mTabList.setFixedMode(true);
// 为TabList配置页签项
for (String tabName : tabs) {
TabList.Tab tab = mTabList.new Tab(this);
tab.setText(tabName);
tab.setTextColor(Color.WHITE);
tab.setTextAlignment(TextAlignment.CENTER);
tab.setFocusable(Component.FOCUS_ENABLE);
mTabList.addTab(tab);
}
}
四、监听tabList选中事件
// 为TabList设置选择页签时的监听
mTabList.addTabSelectedListener(new TabList.TabSelectedListener() {
@Override
public void onSelected(TabList.Tab tab) {
if (tab == null) {
return;
}
FractionManager mFractionManager = ((FractionAbility) getAbility()).getFractionManager();
fractionScheduler = mFractionManager.startFractionScheduler();
HiLog.error(LABEL, "tab.getPosition():%{public}s", tab.getPosition());
if (tab.getPosition() == 0) {
if (fileFraction != null) {
fractionScheduler.hide(fileFraction);
}
//有多个的时候除了需要显示的 其他的都需要隐藏
if (homeFraction == null) {
homeFraction = new HomeFraction();
fractionScheduler.add(ResourceTable.Id_content_layout, homeFraction).show(homeFraction).submit();
} else {
fractionScheduler.show(homeFraction).submit();
}
} else {
if (homeFraction != null) {
fractionScheduler.hide(homeFraction);
}
//有多个的时候除了需要显示的 其他的都需要隐藏
if (fileFraction == null) {
fileFraction = new FileFraction();
fractionScheduler.add(ResourceTable.Id_content_layout, homeFraction).show(fileFraction).submit();
} else {
fractionScheduler.show(fileFraction).submit();
}
}
}
@Override
public void onUnselected(TabList.Tab tab) {
if (tab == null) {
return;
}
HiLog.error(LABEL, "tab1111.getPosition():%{public}s", tab.getPosition());
}
@Override
public void onReselected(TabList.Tab tab) {
}
});
// 设置默认选择的页签项
mTabList.getTabAt(0).select();
}
五、设置默认选中页
mTabList.getTabAt(0).select();
六、Fraction代码
public class FileFraction extends Fraction {
@Override
protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
Component component = scatter.parse(ResourceTable.Layout_file_fraction, container, false);
return component;
}
@Override
protected void onStart(Intent intent) {
super.onStart(intent);
}
@Override
protected void onActive() {
super.onActive();
}
}
homeFraction和File的一样,只是加载的布局不同。