hadss_adaptive:基于自适应库的多场景布局与交互示例项目

提供多设备自适应布局相关组件(边X边X,三分栏等),帮助应用快速适配折叠屏、平板、PC等多种设备。

Branch1Tags0

adaptive

简介

本项目包含三部分示例代码:

1.使用自适应弹窗库和自适应组件库的示例代码,实现的是一个新闻详情页。主要内容包括新闻的边看边评,拖动中间的分割线,自定义跟手弹窗等。

2.使用简化布局库的示例代码, 基于一多开发-便捷生活中的商品页进行修改,主要内容包括横向紧凑与宽松布局的适配。

3.使用自适应视频库中视频自适应沉浸高阶组件的示例代码,实现了短视频滑动播放页面。主要包含视频自适应沉浸高阶组件、播放图标、进度条和Tab栏。

预览

新闻详情页

商品页

横向紧凑布局 横向宽松布局

短视频滑动播放页

工程目录

├── adaptive_dialog     // 自适应弹窗库
├── adaptive_component  // 自适应组件库
├── adaptive_adaptive   // 自适应视频库
├── size_class_layout   // 简化布局库
├── entry               // 工程项目
│   └── src
│       └── main
│           ├── ets
│           │   ├── constants                     // 常量类目录
│           │   ├── entryability
│           │   ├── entrybackupability
│           │   ├── pages
│           │   │   ├── DialogPage.ets             // 弹窗按钮页面
│           │   │   ├── Index.ets                  // 首页
│           │   │   ├── RCLayoutPage.ets           // 简化布局商品页面
│           │   │   ├── VideoPage.ets              // 视频滑动页面
│           │   │   └── SplitContainerPage.ets     // 新闻页面
│           │   ├── utils                         // 断点工具类,弹窗与新闻页面使用
│           │   ├── view                          // 视图页面目录
│           │   └── viewmodel                     // 视图参数信息目录
│           ├── module.json5
│           └── resources
└── README.md           // Sample使用说明

使用adaptive_component库的关键代码

使用AdaptiveSplitContainer组件实现新闻详情页关键代码

@State regionLayoutOptions: RegionLayoutOptions =
  {
    topBarHeight: 61,
    bottomBarHeight: 56,
    horizontalSplitRatio: PresetSplitRatio.LAYOUT_3V2,
    secondaryWidth: 0
  }
@State dividerOptions: DividerOptions = {
  dividerWidth: this.dividerWidth,
  offset: 0,
  leftMaxOffset: '10%',
  rightMaxOffset: '10%',
};
onDividerOffsetChangeHandler: OnDividerOffsetChangeHandler = (dividerOffset: number) => {
  hilog.info(0xFF00, 'NewsSplitContainer', '%{public}s', 'dividerOffset: ' + dividerOffset.toString());
}
onLayoutDirectionChangeHandler: OnLayoutDirectionChangeHandler = (layoutDirection: LayoutDirection) => {
  hilog.info(0xFF00, 'NewsSplitContainer', '%{public}s', 'layoutDirection: ' + layoutDirection.toString());
  this.layoutDirection = layoutDirection;
}
@State layoutDirection: LayoutDirection = LayoutDirection.UNDEFINED;

AdaptiveSplitContainer({
  topBar: () => {
    // 顶部导航栏自定义布局
  },
  bottomBar: () => {
    // 底部导航栏自定义布局
  },
  primary: () => {
    // 左边区域内容自定义布局
  },
  secondary: () => {
    // 右边区域内容自定义布局
  },
  regionLayoutOptions: this.regionLayoutOptions, // 布局参数
  dividerOptions: this.dividerOptions, // 分割线参数
  onDividerOffsetChangeHandler: this.onDividerOffsetChangeHandler, // 右边区域宽度回调函数
  onLayoutDirectionChangeHandler: this.onLayoutDirectionChangeHandler // 布局方向回调函数
})

使用adaptive_dialog库的关键代码

警告弹窗 (AlertDialog)

private showFollowAlertDialog(targetId: string) {
  const dialogId = DialogHelper.showAlertDialog({
    targetId: targetId,
    content: $r('app.string.dialog_content_concern'),
    primaryButton: {
      value: $r('app.string.dialog_cancel'),
      action: () => {
        DialogHelper.closeDialog(dialogId);
      }
    },
    secondaryButton: {
      value: $r('app.string.dialog_confirm'),
      action: () => {
        DialogHelper.closeDialog(dialogId);
      }
    }
  });
}

列表选择弹窗 (ActionSheet)

private showActionSheet(targetId: string) {
  const dialogId = DialogHelper.showActionSheetDialog({
    targetId: targetId,
    title: $r('app.string.dialog_action_sheet_title'),
    subtitle: $r('app.string.dialog_action_sheet_subtitle'),
    sheets: [{
      icon: $r('app.media.view1'),
      title: $r('app.string.dialog_action_title_1'),
      action: () => {
        DialogHelper.closeDialog(dialogId);
      }
    }, {
      icon: $r('app.media.view2'),
      title: $r('app.string.dialog_action_title_2'),
      enabled: true,
      fontColor: Color.Red,
      action: () => {
        DialogHelper.closeDialog(dialogId);
      }
    }, {
      icon: $r('app.media.view3'),
      title: $r('app.string.dialog_action_title_3'),
      action: () => {
        DialogHelper.closeDialog(dialogId);
      }
    }]
  });
}

自定义弹窗 (CustomDialog)

private showShareDialog(targetId: string) {
  const params: ShareDialogParams = {
    targetId: targetId,
    title: $r('app.string.dialog_share_title'),
    message: $r('app.string.dialog_share_message'),
    shareSheet: [{
      icon: $r('app.media.share_forward_btn'),
      tittle: $r('app.string.dialog_share_type_forward'),
      onAction: () => {
        DialogHelper.closeDialog(this.shareDialogId);
      }
    }, {
      icon: $r('app.media.share_recommend_btn'),
      tittle: $r('app.string.dialog_share_type_recommend'),
      onAction: () => {
        DialogHelper.closeDialog(this.shareDialogId);
      }
    }, {
      icon: $r('app.media.share_link_btn'),
      tittle: $r('app.string.dialog_share_type_link'),
      onAction: () => {
        DialogHelper.closeDialog(this.shareDialogId);
      }
    }, {
      icon: $r('app.media.share_popular_btn'),
      tittle: $r('app.string.dialog_share_type_hot'),
      onAction: () => {
        DialogHelper.closeDialog(this.shareDialogId);
      }
    }],
    cancel: () => {
      promptAction.showToast({ message: $r('app.string.toast_cancel_share'), duration: 2000 });
    },
    dialogOptions: {
      alignment: DialogAlignment.Bottom,
      offset: { dx: 0, dy: 0 },
      maskColor: Color.Transparent,
      transition: TransitionEffect.asymmetric(
        TransitionEffect.OPACITY.animation({ duration: 300, curve: Curve.Ease }).combine(
          TransitionEffect.translate({ y: 1000 }).animation({ duration: 300, curve: Curve.Ease })),
        TransitionEffect.OPACITY.animation({ duration: 300, curve: Curve.Ease }).combine(
          TransitionEffect.translate({ y: 1000 }).animation({ duration: 300, curve: Curve.Ease }))
      )
    }
  };
  this.shareDialogId = DialogHelper.showCustomViewDialog(wrapBuilder(ShareDialogBuilder), params);
}

使用size_class_layout的关键代码

窗口级布局

// EntryAbility.ets
export default class EntryAbility extends UIAbility {
  private sizeClassManager: SizeClassManager | undefined = undefined;
  
  onWindowStageCreate(windowStage: window.WindowStage): void {
    windowStage.getMainWindow((err, windowClass) => {
      // ...
      this.sizeClassManager = new SizeClassManager();
      // 获取windowClass后注册窗口监听
      this.sizeClassManager.register();
    });
  }

  onWindowStageWillDestroy(): void {
    this.sizeClassManager?.unregister();
  }
}

// index.ets
@Component
struct RCLayout {
  // 窗口级横向布局状态
  @StorageLink(Constants.HORIZONTAL_PROPNAME) wSizeType: SizeClassType = SizeClassType.ANY;
  // 窗口级纵向布局状态
  @StorageLink(Constants.VERTICAL_PROPNAME) hSizeType: SizeClassType = SizeClassType.ANY;
  
  build() {
    Row() {
      // ...
    }
    // 根据窗口RC状态配置Row容器左内边距
    .padding({
      left: new SizeClassState<string>({
        any: 'auto',
        wRAndHAny: '60%',
        wAnyAndHC: '40%'
      }).getValue({ widthSizeType: this.wSizeType, heightSizeType: this.hSizeType })
    })
  }
}

容器级布局

@Component
struct RCContainerLayout {
  // 定义容器布局规则与布局状态
  private containerRule = new SizeClassRules({ horizontalBorder: 300, verticalBorder: 400 });
  @State containerWSizeType: SizeClassType = SizeClassType.ANY;

  build() {
    Swiper() {
      // ...
    }
    // 根据Swiper容器RC状态设置内部元素展示个数
    .displayCount(new SizeClassState<number>({
      any: 1,
      wCAndHAny: 1,
      wRAndHAny: 2
    }).getValue({ widthSizeType: this.containerWSizeType }))
    // 容器大小变化回调内部更新布局状态
    .onSizeChange((oldValue: SizeOptions, newValue: SizeOptions) => {
      if (typeof newValue.width === 'number' && typeof newValue.height === 'number') {
        // 使用新的容器边界更新布局状态
        this.containerRule.updateSizeClassType({ width: newValue.width ?? 0, height: newValue.height ?? 0 });
        // 获取布局状态以供使用
        this.containerWSizeType = this.bannerRule.getHorizontalSizeClass();
      }
    })
  }
}

布局资源获取

@Component
struct ResLayout {
  // 定义窗口级横向布局状态
  @StorageLink(Constants.HORIZONTAL_PROPNAME) wSizeType: SizeClassType = SizeClassType.ANY;
  
  build() {
    // 根据RC状态获取相应图片资源
    Image(SizeClassResUtils.getRes('image.png', { widthSizeType: this.wSizeType }))
      .height('100%')
      .width('100%')
      .objectFit(ImageFit.Cover)
  }
}

使用adaptive_video中视频自适应沉浸组件的关键代码

短视频滑动场景


// ...
@Component
struct ShortVideoView{
  // ...
  private context = getContext() as common.UIAbilityContext;
  private swiperController: SwiperController = new SwiperController();
  // 实例化一个adaptiveVideoController对象,用于控制当前播放视频播放/暂停等行为。
  private adaptiveVideoController?: AdaptiveVideoController = new AdaptiveVideoController(this.context);
  // 实例化adaptiveVideoListener对象,用于监听视频状态/事件。
  private adaptiveVideoListener?: AdaptiveVideoListener = new AdaptiveVideoListener();
  // 数据源
  private avDataSource = new AVDataSource(Const.VIDEO_SOURCE);
  // 当前正在播放的视频的index
  @State curIndex: number = 0;
  // 状态栏沉浸状态
  @State isStatusBarImmersive: boolean = false;
  // 短视频页面底部tab沉浸状态
  @State isBottomTabImmersive: boolean = false;
  // 当前进度条是否滑动
  @State isSliderMoving: boolean = false;

  // ...
  build(){
    Column(){
      Stack(){
        Swiper(this.swiperController){
          LazyForEach(this.avDataSource, (item: media.AVFileDescriptor | string, index: number) => {
            AdaptiveVideoComponent({
              dataSource: item,
              adaptiveVideoController: this.adaptiveVideoController,
              adaptiveVideoListener: this.adaptiveVideoListener,
              isAutoPlay: true,
              isLoop: true,
              viewMode: ViewMode.SWIPER,
              curIndex: this.curIndex,
              index: index,
              bottomTabHeight: 56,
            })
          }, (item: media.AVFileDescriptor | string, index: number) => JSON.stringify(item) + index)
        }
        .
        cachedCount(2)
        //...
        Row()
        {
          ProgressBar({
            isSliderMoving: this.isSliderMoving,
            adaptiveVideoListener: this.adaptiveVideoListener
          })
        }
      }
    }
  }

  // ...
  // 在页面显示时播放视频
  onPageHide(): void {
    this.adaptiveVideoController?.pause();
  }

  // 在页面隐藏时暂停视频
  onPageShow(): void {
    this.adaptiveVideoController?.play();
  }
}

长视频场景


// ...
@Component 
struct LongVideoView{
  // ...
  private context = getContext() as common.UIAbilityContext;
  // 实例化一个adaptiveVideoController对象,用于控制当前播放视频播放/暂停等行为。
  private adaptiveVideoController?: AdaptiveVideoController = new AdaptiveVideoController(this.context);
  // 实例化adaptiveVideoListener对象,用于监听视频状态/事件。
  private adaptiveVideoListener?: AdaptiveVideoListener = new AdaptiveVideoListener();
  // 数据源
  private avDataSource: media.AVFileDescriptor | string = '';
  // 当前进度条是否滑动
  @State isSliderMoving: boolean = false;

  build(){
    Column(){
      Stack(){
        AdaptiveVideoComponent({
          dataSource: this.avDataSource,
          adaptiveVideoController: this.adaptiveVideoController,
          adaptiveVideoListener: this.adaptiveVideoListener,
          isAutoPlay: true,
          isLoop: true,
          viewMode: ViewMode.FullScreen,
        })
        //...
        Row()
        {
          ProgressBar({
            isSliderMoving: this.isSliderMoving,
            adaptiveVideoListener: this.adaptiveVideoListener
          })
        }
      }
    }
  }

  // ...
  // 在页面显示时播放视频
  onPageHide(): void {
    this.adaptiveVideoController?.pause();
  }

  // 在页面隐藏时暂停视频
  onPageShow(): void {
    this.adaptiveVideoController?.play();
  }
}

约束与限制

  1. 本示例仅支持标准系统上运行,支持设备:华为手机、折叠机、平板、PC。
  2. DevEco Studio 5.0.4(5.0.11.100)及以上, SDK: API14 (5.0.2.123)及以上。

Introduction

提供多设备自适应布局相关组件(边X边X,三分栏等),帮助应用快速适配折叠屏、平板、PC等多种设备。

Customize your domain