PageSlider and PageSliderIndicator for HarmonyOS

Author: Han Ru

Company: Procedural Coffee (Beijing) Technology Co., LTD

Columnist for Hung Mun Bus

The PageSlider is a component that switches between pages by responding to slide events.

1. Supported XML attributes

PageSlider does not have its own XML properties. The total XML properties are inherited from: StackLayout

Second, the use of PageSlider

Create a PageSlider in the XML file in the Layout directory.

<PageSlider
        ohos:id="$+id:page_slider"
        ohos:height="300vp"
        ohos:width="300vp"
        ohos:background_element="#33aa0000"
        ohos:layout_alignment="horizontal_center"/>

Effect:

<img src=”https://img.chengxuka.com/[email protected]/mark” alt=”WX20210616-114314@2x” style=”zoom:50%;” />

2, each page may need to present different data, so need to adapt to different data structure, need to use PageSliderProvider.

The method name role
getCount() Gets the number of views available.
createPageInContainer(ComponentContainer componentContainer, int position) Creates the page at the specified location.
destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) Destroys the specified page in the container.
isPageMatchToObject(Component component, Object o) Whether the view is associated with a specified object.

Create a new provider package and create testPageProvider.java, which inherits from PagesliderProvider.java. You must override the following methods:

Sample code:

package com.example.hanrupageslider.provider; import ohos.agp.colors.RgbColor; import ohos.agp.components.*; import ohos.agp.components.element.ShapeElement; import ohos.agp.utils.Color; import ohos.agp.utils.TextAlignment; import java.util.List; /** * extends PageSliderProvider */ public class TestPagerProvider extends PageSliderProvider {// Data source, Private list <DataItem> list; public TestPagerProvider(List<DataItem> list) { this.list = list; } /** * Indicates the number of data items loaded on the Provider * @return Indicates the number of data items in the Provider */ @override public int getCount() {return list.size(); ** @param componentContainer ** @param componentContainer ** @param componentContainer ** @param componentContainer ** @param componentContainer ** @param componentContainer ** @param componentContainer ** @param componentContainer ** @param componentContainer * @Override public Object createPageInContainer(ComponentContainer ComponentContainer, int position) { // 1. Final DataItem data = list.get(position); // 2. Create a Text object and set the Text label = new Text(null); label.setTextAlignment(TextAlignment.CENTER); label.setLayoutConfig( new StackLayout.LayoutConfig( ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT )); label.setText(data.mText); label.setTextColor(Color.BLACK); label.setTextSize(50); ShapeElement element = new ShapeElement(); element.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor("#AFEEEE"))); label.setBackground(element); / / 3. Will just create a Text object, loading into PageSlider componentContainer. AddComponent (label); return label; } @param componentContainer * @param componentContainer * @param componentContainer * @param position * @param componentContainer * @param Position * @param */ @Override public void destroyPageFromContainer(ComponentContainer ComponentContainer, int position, Object object) { componentContainer.removeComponent((Component) object); } /** * Whether the view is associated with the specified object. * @param component * @param object * @return */ @Override public boolean isPageMatchToObject(Component component, Object object) { return true; } public static class DataItem{String mText; public DataItem(String txt) { mText = txt; }}}

3, MainAbilitySlice, add data, and match PageSlider data structure.

package com.example.hanrupageslider.slice; import com.example.hanrupageslider.ResourceTable; import com.example.hanrupageslider.provider.TestPagerProvider; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.agp.components.PageSlider; import java.util.ArrayList; / * * * PageSlider mainly through the slide show about data control * PageSlider data display in the list So belong to the Provider controls * / public class MainAbilitySlice extends AbilitySlice { @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_main); initPageSlider(); Private void initPageSlider() {PageSlider PageSlider = (PageSlider) findComponentById(ResourceTable.Id_page_slider); pageSlider.setProvider(new TestPagerProvider(getData())); } / / 2. To provide data source private ArrayList < TestPagerProvider. DataItem > getData () {ArrayList < TestPagerProvider. DataItem > dataItems =  new ArrayList<>(); dataItems.add(new TestPagerProvider.DataItem("Page A")); dataItems.add(new TestPagerProvider.DataItem("Page B")); dataItems.add(new TestPagerProvider.DataItem("Page C")); dataItems.add(new TestPagerProvider.DataItem("Page D")); return dataItems; } @Override public void onActive() { super.onActive(); } @Override public void onForeground(Intent intent) { super.onForeground(intent); }}

PageSlider:

<img src=”https://img.chengxuka.com/pageslideryunxing1.gif” alt=”pageslideryunxing1″ style=”zoom:50%;” />

Three, PageSlider common methods

Table of Common methods

The method name role
setProvider(PageSliderProvider provider) Set the Provider to configure the PageSlider data structure.
addPageChangedListener(PageChangedListener listener) Responds to the page switchover event.
removePageChangedListener(PageChangedListener listener) Remove page switching response.
setOrientation(int orientation) Set the layout direction.
setPageCacheSize(int count) Sets the number of pages to keep on both sides of the current page.
setCurrentPage(int itemPos) Set the current display page.
setCurrentPage(int itemPos, boolean smoothScroll) Set the current display and determine whether smooth scrolling is required.
setSlidingPossible(boolean enable) Whether to enable page swiping.
setReboundEffect(boolean enabled) Whether to enable the rebound effect.
setReboundEffectParams(int overscrollPercent, float overscrollRate,int remainVisiblePercent)setReboundEffectParams(ReboundEffectParams reboundEffectParams) The springback effect parameters are configured.
setPageSwitchTime(int durationMs) Set the page switching time.

1. Respond to the page switchover event

        pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int itemPos, float itemPosOffset, int itemPosPixles) { 
            }
            @Override
            public void onPageSlideStateChanged(int state) { 
            }
            @Override
            public void onPageChosen(int itemPos) { 
            }
        });

2. Set the layout direction. The default layout is horizontal

Set in XML:

<PageSlider
    ...
    ohos:orientation="vertical"/>

In the code set:

pageSlider.setOrientation(Component.VERTICAL);

Set the layout direction to portrait

<img src=”https://img.chengxuka.com/pageslideryunxing2.gif” alt=”pageslideryunxing2″ style=”zoom:50%;” />

3. Set the number of reserved pages on both sides of the current page

Set in XML:

<PageSlider
    ...
    ohos:page_cache_size="2"/>

In the code set:

pageSlider.setPageCacheSize(2);

4. Set the current display page

pageSlider.setCurrentPage(2);

Sample code:

Private void initPageSlider() {PageSlider PageSlider = (PageSlider) findComponentById(ResourceTable.Id_page_slider); pageSlider.setProvider(new TestPagerProvider(getData())); / / set the current display page, starting from 0 pageSlider. SetCurrentPage (2); // Page C }

When opened, the third Page is displayed by default:

<img src=”https://img.chengxuka.com/[email protected]/mark” alt=”WX20210616-135723@2x” style=”zoom:50%;” />

Scroll smoothly to the specified page

pageSlider.setCurrentPage(2,true); // Page C

Smooth scrolling to page C effect: The emulator is too slow to see the smooth scrolling effect, here is the official document image.

5. Set whether to enable page sliding

ageSlider.setSlidingPossible(false);

6. Set the springback effect

pageSlider.setReboundEffect(true);

Rebound effect: Image from official document.

7. Set the page switching time, unit: ms

pageSlider.setPageSwitchTime(2000);

PageSliderIndicator

The PageSliderIndicator should be used together with the PageSlider to indicate which interface to display in the PageSlider.

1. We continue to add PageSliderIndicator in ability_main. XML.

<? The 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"> <PageSlider ohos:id="$+id:page_slider" ohos:height="300vp" ohos:width="300vp" ohos:background_element="#33aa0000" ohos:layout_alignment="horizontal_center"/> <! -- ohos:orientation="vertical" --> <! -- ohos:page_cache_size="2" , <PageSliderIndicator ohos:id="$+id:indicator" ohos:height="match_content" ohos:width="match_content" ohos:padding="8vp" ohos:layout_alignment="horizontal_center" ohos:top_margin="16vp" ohos:background_element="#55FFC0CB"/> </DirectionalLayout>

MainAbilitySlice. Java initPageSlider() create the PageSliderIndicator and set it to the PageSlider object.

Private void initPageSlider() {PageSlider PageSlider = (PageSlider) findComponentById(ResourceTable.Id_page_slider); pageSlider.setProvider(new TestPagerProvider(getData())); / / set the springback effect pageSlider setReboundEffect (true); / / Settings page switching time, the unit: ms pageSlider. SetPageSwitchTime (2000); / / set the current display page, starting from 0. / / pageSlider setCurrentPage (2); / / / / smooth scrolling Page C to the specified Page pageSlider. SetCurrentPage (2, true); // Page C // Create PageSliderIndicator PageSliderIndicator indicator = (PageSliderIndicator)findComponentById(ResourceTable.Id_indicator); ShapeElement normalElement = new ShapeElement(); normalElement.setRgbColor(RgbColor.fromArgbInt(0xADD8E6)); normalElement.setAlpha(168); normalElement.setShape(ShapeElement.OVAL); normalElement.setBounds(0, 0, 32, 32); ShapeElement selectedElement = new ShapeElement(); selectedElement.setRgbColor(RgbColor.fromArgbInt(0x00BFFF)); selectedElement.setAlpha(168); selectedElement.setShape(ShapeElement.OVAL); selectedElement.setBounds(0, 0, 48, 48); indicator.setItemElement(normalElement, selectedElement); indicator.setItemOffset(60); / / set the indicator. SetPageSlider (pageSlider); }

With the PageSlider effect:

<img src=”https://img.chengxuka.com/pageslideryunxing3.gif” alt=”pageslideryunxing3″ style=”zoom:50%;” />

PageSliderIndicator

1, associate PageSlider

indicator.setPageSlider(pageSlider);

2. Respond to page change events

    indicator.addOnSelectionChangedListener(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) {
            }
        });

3. Set the position of the selected navigation point

indicator.setSelected(2);

This method also changes the page in the associated PageSlider object.

4. Set the background of the navigation point

In addition to creating backgrounds in Java as described above, you can also create them using XML.

Create selected_page_bg_element.xml in the Graphic folder.

<? The XML version = "1.0" encoding = "utf-8"? > <shape xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:shape="rectangle"> <corners ohos:radius="16vp"/> <bounds ohos:top="0" ohos:left="0" ohos:right="64vp" ohos:bottom="32vp"/> <solid ohos:color="#00BFFF"/> </shape>

Create unselected_page_bg_element.xml in the Graphic folder.

<? The XML version = "1.0" encoding = "utf-8"? > <shape xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:shape="oval"> <bounds ohos:top="0" ohos:left="0" ohos:right="32vp" ohos:bottom="32vp"/> <solid ohos:color="#ADD8E6"/> </shape>

Called in Java code to set the navigation point background.

    ShapeElement normalElement = new ShapeElement(this, ResourceTable.Graphic_unselected_page_bg_element);
        ShapeElement selectedElement = new ShapeElement(this, ResourceTable.Graphic_selected_page_bg_element);
        indicator.setItemElement(normalElement, selectedElement);

Navigation point background setting effect:

<img src=”https://img.chengxuka.com/pageslideryunxing4.gif” alt=”pageslideryunxing4″ style=”zoom:50%;” />

5. Set the offset between navigation points

// Set indicator. SetItemOffset (100); / / set the indicator. SetPageSlider (pageSlider);

Effect:

<img src=”https://img.chengxuka.com/[email protected]/mark” alt=”WX20210616-143633@2x” style=”zoom:50%;” />

More:

1, community: https://www.harmonybus.net/ HongMeng bus

2. Official account: HarmonyBus

3, technical exchange QQ group: 714518656

Lesson 4, video: https://www.chengxuka.com