【鸿蒙】HarMonyOS的UI组件学习七之图片轮播

图片轮播功能也是我们在很多应用中常见的一种效果,今天分享鸿蒙系统中展示图片轮播功能。

在鸿蒙系统中,实现轮播效果,主要使用PageSlider组件

接下来创建主布局,代码如下:

<?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">

    <PageSlider
        ohos:id="$+id:ps"
        ohos:height="200fp"
        ohos:orientation="horizontal"
        ohos:width="match_parent"/>

</DirectionalLayout>

ohos:orientation="horizontal"设置轮播滑动方向为横向

private int[] images = {
            ResourceTable.Media_jinriteyue,
            ResourceTable.Media_ydqbannerbeihai,
            ResourceTable.Media_ydqbannershouti,
            ResourceTable.Media_i_back,
            ResourceTable.Media_spic};
    private String[] names={
            "第一张图",
            "第二张图",
            "第三张图",
            "第四张图",
            "第五张图"
    };

添加五张图片,定义其图片的引用id数组和每张图片对应的文字信息数组

定义实体类,将图片和文字封装成实体类

package com.example.hm_phone_java.entity;

public class Page {
    private int image;
    private String name;

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Page(int image, String name) {
        this.image = image;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Page{" +
                "image=" + image +
                ", name='" + name + '\'' +
                '}';
    }
}

定义集合存储所有封装好的实体类

private List<Page> pages=new ArrayList<>();

将数据进行封装

private void initPage() {
        for (int i = 0; i < images.length; i++) {
            Page page=new Page(images[i],names[i]);
            pages.add(page);
        }
    }

创建滑动页面组件的适配器类

package com.example.hm_phone_java.adapter;

import com.example.hm_phone_java.entity.Page;
import ohos.aafwk.ability.AbilitySlice;
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;

public class PageItemAdapter extends PageSliderProvider {

    private List<Page> pages;
    private AbilitySlice context;

    public PageItemAdapter(List<Page> pages,AbilitySlice context) {
        this.pages = pages;
        this.context=context;
    }

    @Override
    public int getCount() {
        return pages.size();
    }

    @Override
    public Object createPageInContainer(ComponentContainer componentContainer, int i) {
        Page page=pages.get(i);
        //创建图片组件
        Image image=new Image(context);
        //创建文本组件
        Text text=new Text(context);
        //设置图片平铺Image组件的所有宽高
        image.setScaleMode(Image.ScaleMode.STRETCH);
        //设置图片的高宽
        image.setLayoutConfig(
                new StackLayout.LayoutConfig(
                        StackLayout.LayoutConfig.MATCH_PARENT,
                        StackLayout.LayoutConfig.MATCH_PARENT));
        //添加图片
        image.setPixelMap(pages.get(i).getImage());
        StackLayout.LayoutConfig lc=new StackLayout.LayoutConfig(
                StackLayout.LayoutConfig.MATCH_PARENT,
                StackLayout.LayoutConfig.MATCH_CONTENT);
        //设置文本高宽
        text.setLayoutConfig(lc);
        //设置文本对齐方式
        text.setTextAlignment(TextAlignment.CENTER);
        //设置文本文字
        text.setText(pages.get(i).getName());
        //设置文本大小
        text.setTextSize(80);
        //设置相对于其他组件的对齐方式
        //设置文字颜色为白色
        text.setTextColor(Color.WHITE);
        //设置文本背景颜色
        RgbColor color=new RgbColor(100,100,100);
        ShapeElement se=new ShapeElement();
        se.setRgbColor(color);
        text.setBackground(se);
        //创建层布局
        StackLayout sl=new StackLayout(context);
        sl.setLayoutConfig(new StackLayout.LayoutConfig(StackLayout.LayoutConfig.MATCH_PARENT,
                StackLayout.LayoutConfig.MATCH_PARENT));
        //将图片和文本组件添加至层布局
        sl.addComponent(image);
        sl.addComponent(text);
        //将层布局放入滑页组件中
        componentContainer.addComponent(sl);
        return sl;
    }

    @Override
    public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
        //滑出屏幕的组件进行移除
        componentContainer.removeComponent((Component) o);
    }

    @Override
    public boolean isPageMatchToObject(Component component, Object o) {
        //判断滑页上的每一页的组件和内容是否保持一致
        return true;
    }


}

适配器中采用java代码动态创建子布局的形式,这里也可以使用xml的方式创建子布局然后进行加载进来,这里就不做操作了,可以自行调整页面

接着主界面上定义适配器

private PageItemAdapter adapter;

重写onStart方法,加载主布局,根据id获得滑动页面对象

 @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
//加载主布局
        this.setUIContent(ResourceTable.Layout_ability_page);
//根据id获得滑动页面组件对象
        PageSlider ps = (PageSlider) this.findComponentById(ResourceTable.Id_ps);
//初始化图片和文字数据封装在集合中
        initPage();
//创建适配器对象,将当前界面对象和封装好的集合发送过去
        adapter=new PageItemAdapter(pages,this);
//将适配器加载至滑动组件上,完成同步组装
        ps.setProvider(adapter);

    }

接下来开启华为模拟器,运行项目即可,界面可以自行设计的更美观。

至此该文章分享到这里,感谢大家的关注和阅读,后期会分享更多鸿蒙技术文章!!!

需要相关图片的,可以使用:

下一篇 【鸿蒙】HarMonyOS的UI组件学习八之网站引入

### HarmonyOS 中实现图片轮播鸿蒙操作系统(HarmonyOS)中创建一个能够展示多张图片并支持自动以及手动切换的轮播图功能,可以通过利用`@ohos.multimedia.image`模块以及其他UI组件来完成。下面提供一段基于HarmonyOS环境下的简单示例代码用于说明如何构建这样的特性。 #### 创建XML布局文件 首先定义页面上的控件,在ability_main.xml或其他相应的xml文件里加入如下代码: ```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"> <!-- 轮播视图 --> <SwipeView ohos:id="$+id:image_swipe_view" ohos:height="match_content" ohos:width="match_parent"/> <!-- 底部指示器容器 --> <StackLayout ohos:id="$+id:indicator_container" ohos:height="20vp" ohos:width="match_parent"> <!-- 这里放置代表当前页码的小圆点或者其他形式的指示符 --> </StackLayout> </DirectionalLayout> ``` #### 编写Ability逻辑处理部分 接着是在对应的Java/Kotlin Ability类里面编写业务逻辑,这里给出Kotlin版本的例子: ```kotlin import com.example.myapplication.ResourceTable import ohos.aafwk.ability.Ability import ohos.agp.components.SwipeView import ohos.agp.utils.LayoutAlignment import ohos.app.Context import java.util.* class MainAbility : Ability() { private lateinit var swipeView: SwipeView override fun onStart(want: Want?) { super.onStart(want) setMainRoute(MainAbilitySlice::class.java.name) } } class MainAbilitySlice : AbilitySlice() { val imageUrls = listOf( "https://example.com/image1.jpg", "https://example.com/image2.jpg", "https://example.com/image3.jpg" ) override fun onStart(intent: Intent?) { super.onStart(intent) // 加载界面资源 setContentView(ResourceTable.Layout_ability_main) // 初始化SwipeView对象 swipeView = findComponentById(ResourceTable.Id_image_swipe_view) // 设置适配器给swipeview, 并传入数据源imageUrls swipeView.adapter = ImageAdapter(this.context as Context, imageUrls) // 添加滑动监听事件... swipeView.setPageChangedListener(object : SwipeView.PageChangedListener{ override fun onPageSelected(position: Int){ updateIndicator(position) } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int){ /* ... */ } override fun onPageScrollStateChanged(state: Int){} }) } /** * 更新底部指示器状态的方法 */ private fun updateIndicator(index:Int){ // 根据index更新底部指示器的状态 } } ``` 上述代码片段展示了基本框架结构[^1],其中包含了设置SwipeView作为承载多个ImageViews的基础容器,并通过自定义adapter加载网络图片列表;同时设置了page change listener以便于同步底部指示器的位置变化。 为了使这个例子更加完善,还需要进一步补充ImageAdapter的具体实现细节,比如下载远程图片、缓存机制等优化措施。此外,对于本地存储中的静态图像路径同样适用此方法。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笔触狂放

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值