4.6 HarmonyOS Developed PageSlider and PageSliderIndicator
Author: Han Ru
Company: Program Ka (Beijing) Technology Co., LTD
Hong Meng Bus columnist
PageSlider is a component that switches between pages by responding to sliding events.
Supported XML attributes
PageSlider has no XML attributes of its own, but all XML attributes are inherited from StackLayout
How to use PageSlider
1. Create PageSlider in XML file in Layout directory.
<PageSlider
ohos:id="$+id:page_slider"
ohos:height="300vp"
ohos:width="300vp"
ohos:background_element="#33aa0000"
ohos:layout_alignment="horizontal_center"/>
Copy the code
Effect:
2. Each page may need to present different data, so it needs to adapt to different data structures, using PageSliderProvider.
The method name | role |
---|---|
getCount() | Gets the number of available views. |
createPageInContainer(ComponentContainer componentContainer, int position) | Creates a 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 associates the specified object. |
Create a provider package that inherits PagesliderProvider.java and 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;
/** * Inherit PageSliderProvider */
public class TestPagerProvider extends PageSliderProvider {
// Data source, each page corresponds to an item in the list
private List<DataItem> list;
public TestPagerProvider(List<DataItem> list) {
this.list = list;
}
/** * indicates the entry in the current Provider to load data *@returnThe return value represents the number of data entries in the Provider */
@Override
public int getCount(a) {
return list.size();
}
/** * instantiates each page in PageSlider according to the subscript **@paramComponentContainer, which represents the PageSlider control to which the instantiated Item belongs@paramPosition, representing the current instantiation subscript *@return* /
@Override
public Object createPageInContainer(ComponentContainer componentContainer, int position) {
// 1. Obtain data from subscripts
final DataItem data = list.get(position);
// 2. Create a Text object and set the Text
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. Load the newly created Text object into PageSlider
componentContainer.addComponent(label);
return label;
}
/** * removes the pager page * from PageSlider by subscript@paramComponentContainer, which represents the PageSlider control * to which the currently removed Pager page belongs@paramPosition, which removes the subscript * of the page@param object
*/
@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;
}
// Data entity class
public static class DataItem{
String mText;
public DataItem(String txt) { mText = txt; }}}Copy the code
3, In MainAbilitySlice, add data, and adapt 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 is a Provider control that displays a list of data
public class MainAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
initPageSlider();
}
Initialize PageSlider
private void initPageSlider(a) {
PageSlider pageSlider = (PageSlider) findComponentById(ResourceTable.Id_page_slider);
pageSlider.setProvider(new TestPagerProvider(getData()));
}
// 2. Provide a 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(a) {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent); }}Copy the code
PageSlider works like this:
PageSlider common methods
Table of common Methods
The method name | role |
---|---|
setProvider(PageSliderProvider provider) | Set up the Provider to configure the PageSlider data structure. |
addPageChangedListener(PageChangedListener listener) | Respond to the page switch event. |
removePageChangedListener(PageChangedListener listener) | Removes the page switch response. |
setOrientation(int orientation) | Set the layout direction. |
setPageCacheSize(int count) | Set 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 sliding. |
setReboundEffect(boolean enabled) | Whether to enable the rebound effect. |
setReboundEffectParams(int overscrollPercent, float overscrollRate,int remainVisiblePercent)setReboundEffectParams(ReboundEffectParams reboundEffectParams) | Set the springback effect parameters. |
setPageSwitchTime(int durationMs) | Set the page switching time. |
1. Respond to the page switching 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) {}});Copy the code
2. Set the layout direction. The default layout is landscape
Set in XML:
<PageSlider
...
ohos:orientation="vertical"/>
Copy the code
Set in code:
pageSlider.setOrientation(Component.VERTICAL);
Copy the code
Set the layout direction to vertical
3. Set the number of pages on both sides of the current page
Set in XML:
<PageSlider
...
ohos:page_cache_size="2"/>
Copy the code
Set in code:
pageSlider.setPageCacheSize(2);
Copy the code
4. Set the current display page
pageSlider.setCurrentPage(2);
Copy the code
Sample code:
Initialize PageSlider
private void initPageSlider(a) {
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
}
Copy the code
When opened, Page 3 is displayed by default:
Smooth scrolling to the specified page
pageSlider.setCurrentPage(2.true); // Page C
Copy the code
Smooth scrolling to page C effect: The emulator is too stuck to see smooth scrolling, so here is the official document image.
5. Set whether to enable page sliding
ageSlider.setSlidingPossible(false);
Copy the code
6. Set the rebound effect
pageSlider.setReboundEffect(true);
Copy the code
Rebound effect: Image from official documentation.
7. Set page switching time (unit: ms)
pageSlider.setPageSwitchTime(2000);
Copy the code
Component PageSliderIndicator
PageSliderIndicator, which should be used in conjunction with PageSlider to indicate which interface to display in PageSlider.
1. We added PageSliderIndicator to 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: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", slide direction, default level --> <! -- 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>
Copy the code
In MainAbilitySlice. Java initPageSlider(), create PageSliderIndicator and set it to PageSlider.
Initialize PageSlider
private void initPageSlider(a) {
PageSlider pageSlider = (PageSlider) findComponentById(ResourceTable.Id_page_slider);
pageSlider.setProvider(new TestPagerProvider(getData()));
// Set the springback effect
pageSlider.setReboundEffect(true);
// Set the page switching time, unit: ms
pageSlider.setPageSwitchTime(2000);
// Set the current display page, starting from 0
// pageSlider.setCurrentPage(2); // Page C
// Scroll smoothly 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
indicator.setPageSlider(pageSlider);
}
Copy the code
With PageSlider effect:
PageSliderIndicator
1. Associate PageSlider
indicator.setPageSlider(pageSlider);
Copy the code
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) {}});Copy the code
3. Set the position of the selected guidance navigation point
indicator.setSelected(2);
Copy the code
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, you can also create them in XML.
Create selected_page_bg_element.xml in the graphic folder.
<? 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>
Copy the code
Create unselected_page_bg_element.xml in the graphic folder.
<? 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>
Copy the code
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);
Copy the code
Navigation background Settings:
5. Set the offset between navigation points
// Set the offset between navigation points
indicator.setItemOffset(100);
/ / set
indicator.setPageSlider(pageSlider);
Copy the code
Effect:
More:
1. Community: Hongmeng Bus www.harmonybus.net/
2. HarmonyBus
3, technical exchange QQ group: 714518656
4. Video courses: www.chengxuka.com