什么是PageSlider、PageSliderIndicator
PageSlider是用于实现整页切换.
PageSliderIndicator用于辅助显示当前所处页面。
效果图:
基础用法
- 在主布局文件"ability_main.xml"中增加
PageSlider
和PageSliderIndicator
<StackLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent">
<PageSlider
ohos:id="$+id:pager_slider"
ohos:height="match_parent"
ohos:width="match_parent"/>
<PageSliderIndicator
ohos:id="$+id:page_slider_indicator"
ohos:height="match_content"
ohos:width="match_content"
ohos:item_offset="60vp"
ohos:layout_alignment="bottom|horizontal_center"
ohos:padding="8vp"/>
</StackLayout>
- 在Slice中实例化PageSlider,设置数据
public class MainAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
PageSlider pageSlider = (PageSlider) findComponentById(ResourceTable.Id_pager_slider);
LayoutScatter layoutScatter = LayoutScatter.getInstance(getContext());
Component component1 = layoutScatter.parse(ResourceTable.Layout_page1, null, false);
Component component2 = layoutScatter.parse(ResourceTable.Layout_page2, null, false);
List<Component> components = new ArrayList<>();
components.add(component1);
components.add(component2);
pageSlider.setProvider(new PageSliderProvider() {
@Override
public int getCount() {
return components.size();
}
@Override
public Object createPageInContainer(ComponentContainer componentContainer, int i) {
componentContainer.addComponent(components.get(i));
return components.get(i);
}
@Override
public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
componentContainer.removeComponent(components.get(i));
}
@Override
public boolean isPageMatchToObject(Component component, Object o) {
return component == o;
}
});
PageSliderIndicator pageSliderIndicator = (PageSliderIndicator) findComponentById(ResourceTable.Id_page_slider_indicator);
pageSliderIndicator.setPageSlider(pageSlider);
}
}
- 两个页面对应代码:
- page1.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">
<Text
ohos:height="match_parent"
ohos:width="match_parent"
ohos:text="PageSlider1"
ohos:text_alignment="center"
ohos:text_size="25fp"/>
</DirectionalLayout>
- page2.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">
<Text
ohos:height="match_parent"
ohos:width="match_parent"
ohos:text="PageSlider2"
ohos:text_alignment="center"
ohos:text_size="25fp"/>
</DirectionalLayout>
完整源代码
https://gitee.com/hspbc/harmonyos_demos/tree/master/pageSliderDemo
关于我
厦门大学计算机专业 | 前华为工程师
分享编程技术,没啥深度,但看得懂,适合初学者。
Java | 安卓 | 前端 | 小程序 | 鸿蒙
公众号:花生皮编程
网友评论