未验证 提交 4e6108b1 编写于 作者: O openharmony_ci 提交者: Gitee

!23966 update api ui md

Merge pull request !23966 from 李欣楠/master
......@@ -585,7 +585,9 @@ getSystemFontList(): Array\<string>
```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
let font:Font|undefined = uiContext.getFont();
font.getSystemFontList()
if(font){
font.getSystemFontList()
}
```
### getFontByName
......@@ -613,7 +615,9 @@ getFontByName(fontName: string): font.FontInfo
```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
let font:Font|undefined = uiContext.getFont();
font.getFontByName('Sans Italic')
if(font){
font.getFontByName('Sans Italic')
}
```
## ComponentUtils
......@@ -753,7 +757,7 @@ pushUrl(options: router.RouterOptions): Promise&lt;void&gt;
```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter();
let router:Router = uiContext.getRouter();
try {
router.pushUrl({
url: 'pages/routerpage2',
......@@ -801,7 +805,7 @@ pushUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;): voi
```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter();
let router:Router = uiContext.getRouter();
router.pushUrl({
url: 'pages/routerpage2',
params: {
......@@ -970,7 +974,7 @@ replaceUrl(options: router.RouterOptions): Promise&lt;void&gt;
```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter();
let router:Router = uiContext.getRouter();
try {
router.replaceUrl({
url: 'pages/detail',
......@@ -1014,7 +1018,7 @@ replaceUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;):
```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter();
let router:Router = uiContext.getRouter();
router.replaceUrl({
url: 'pages/detail',
params: {
......@@ -1173,7 +1177,7 @@ pushNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt;
```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter();
let router:Router = uiContext.getRouter();
try {
router.pushNamedRoute({
name: 'myPage',
......@@ -1221,7 +1225,7 @@ pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt;vo
```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter();
let router:Router = uiContext.getRouter();
router.pushNamedRoute({
name: 'myPage',
params: {
......@@ -1389,7 +1393,7 @@ replaceNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt;
```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter();
let router:Router = uiContext.getRouter();
try {
router.replaceNamedRoute({
name: 'myPage',
......@@ -1433,7 +1437,7 @@ replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt
```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter();
let router:Router = uiContext.getRouter();
router.replaceNamedRoute({
name: 'myPage',
params: {
......
......@@ -11,7 +11,13 @@ UI界面除了运行动画之外,还承载着与用户进行实时交互的功
```ts
import curves from '@ohos.curves'
class SetSlt{
scaleToggle:boolean = true
set():void{
this.scaleToggle = !this.scaleToggle;
}
}
let CurAn:Record<string,curves> = {'curve':curves.springMotion()}
// 第一步:声明相关状态变量
@state scaleToggle: boolean = true;
......@@ -25,9 +31,7 @@ Column() {
this.scaleToggle = !this.scaleToggle;
})
// 第四步:通过隐式动画接口开启隐式动画,动画终点值改变时,系统自动添加衔接动画
.animation({
curve: curves.springMotion()
})
.animation(CurAn)
}
...
```
......@@ -37,7 +41,13 @@ Column() {
```ts
import curves from '@ohos.curves';
class SetSlt{
scaleToggle:boolean = true
set():void{
this.scaleToggle = !this.scaleToggle;
}
}
let CurAn:Record<string,curves> = {'curve':curves.springMotion()}
@Entry
@Component
struct AnimationToAnimationDemo {
......@@ -60,7 +70,8 @@ struct AnimationToAnimationDemo {
Button('Click')
.margin({ top: 200 })
.onClick(() => {
this.isAnimation = !this.isAnimation;
let sets = new SetSlt()
sets.set()
})
}
.width('100%')
......@@ -85,7 +96,14 @@ struct AnimationToAnimationDemo {
```ts
import curves from '@ohos.curves'
class SetOffset{
offsetX:number = 0;
offsetY:number = 0;
set(x:number,y:number):void{
this.offsetX = x;
this.offsetY = y;
}
}
// 第一步:声明相关状态变量
@state offsetX: number = 0;
@State offsetY: number = 0;
......@@ -97,13 +115,15 @@ Column()
.translate({ x: this.offsetX, y: this.offsetY})
.gesture(
PanGesture({})
.onActionUpdate((event: GestureEvent) => {
.onActionUpdate((event?: GestureEvent) => {
// 第三步:在跟手过程改变状态变量值,并且采用reponsiveSpringMotion动画运动到新的值
animateTo({
curve: curves.responsiveSpringMotion()
}, () => {
this.offsetX = event.offsetX;
this.offsetY = event.offsetY;
if(event){
let setxy = new SetOffset();
setxy.set(event.offsetX,event.offsetY)
}
})
})
.onActionEnd(() => {
......@@ -111,8 +131,8 @@ Column()
animateTo({
curve: curves.SpringMotion()
}, () => {
this.offsetX = targetOffsetX;
this.offsetY = targetOffsetY;
let setxy = new SetOffset();
setxy.set(targetOffsetX,targetOffsetY)
})
})
)
......@@ -124,7 +144,20 @@ Column()
```ts
import curves from '@ohos.curves';
class SetOffset{
offsetX:number = 0;
offsetY:number = 0;
positionX:number = 100;
positionY:number = 100;
set(x:number,y:number):void{
this.offsetX = x;
this.offsetY = y;
}
setJ(x:number,y:number,diameter:number = 50):void{
this.positionX = x - diameter / 2;
this.positionY = y - diameter / 2;
}
}
@Entry
@Component
struct SpringMotionDemo {
......@@ -138,22 +171,24 @@ struct SpringMotionDemo {
Circle({ width: this.diameter, height: this.diameter })
.fill(Color.Blue)
.position({ x: this.positionX, y: this.positionY })
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Move) {
// 跟手过程,使用responsiveSpringMotion曲线
animateTo({ curve: curves.responsiveSpringMotion() }, () => {
// 减去半径,以使球的中心运动到手指位置
this.positionX = event.touches[0].screenX - this.diameter / 2;
this.positionY = event.touches[0].screenY - this.diameter / 2;
console.info(`move, animateTo x:${this.positionX}, y:${this.positionY}`);
})
} else if (event.type === TouchType.Up) {
// 离手时,使用springMotion曲线
animateTo({ curve: curves.springMotion() }, () => {
this.positionX = 100;
this.positionY = 100;
console.info(`touchUp, animateTo x:100, y:100`);
})
.onTouch((event?: TouchEvent) => {
if(event){
if (event.type === TouchType.Move) {
// 跟手过程,使用responsiveSpringMotion曲线
animateTo({ curve: curves.responsiveSpringMotion() }, () => {
// 减去半径,以使球的中心运动到手指位置
let setxy = new SetOffset();
setxy.setJ(event.touches[0].screenX,event.touches[0].screenY,this.diameter)
console.info(`move, animateTo x:${setxy.positionX}, y:${setxy.positionY}`);
})
} else if (event.type === TouchType.Up) {
// 离手时,使用springMotion曲线
animateTo({ curve: curves.springMotion() }, () => {
let setxy = new SetOffset();
setxy.set(100,100)
console.info(`touchUp, animateTo x:100, y:100`);
})
}
}
})
}
......
......@@ -133,8 +133,8 @@ Button有三种可选类型,分别为Capsule(胶囊类型)、Circle(圆
为删除操作创建一个按钮。
```ts
Button({ type: ButtonType.Circle, stateEffect: true }) {
Image($r('app.media.ic_public_delete_filled')).width(30).height(30)
Button({ type: ButtonType.Circle, stateEffect: true }) {
Image($r('app.media.ic_public_delete_filled')).width(30).height(30)
}.width(55).height(55).margin({ left: 20 }).backgroundColor(0xF55A42)
```
......@@ -162,6 +162,9 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true })
```ts
// xxx.ets
import router from '@ohos.router';
let furl:Record<string,string> = {'url':'pages/first_page'}
let surl:Record<string,string> = {'url':'pages/second_page'}
let turl:Record<string,string> = {'url':'pages/third_page'}
@Entry
@Component
struct ButtonCase1 {
......@@ -169,19 +172,19 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true })
List({ space: 4 }) {
ListItem() {
Button("First").onClick(() => {
router.pushUrl({ url: 'pages/first_page' })
router.pushUrl(furl)
})
.width('100%')
}
ListItem() {
Button("Second").onClick(() => {
router.pushUrl({ url: 'pages/second_page' })
router.pushUrl(surl)
})
.width('100%')
}
ListItem() {
Button("Third").onClick(() => {
router.pushUrl({ url: 'pages/third_page' })
router.pushUrl(turl)
})
.width('100%')
}
......@@ -232,13 +235,13 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true })
build() {
Stack() {
List({ space: 20, initialIndex: 0 }) {
ForEach(this.arr, (item) => {
ForEach(this.arr, (item:number) => {
ListItem() {
Text('' + item)
.width('100%').height(100).fontSize(16)
.textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF)
}
}, item => item)
}, ((item:number):number => item))
}.width('90%')
Button() {
Image($r('app.media.ic_public_add'))
......
......@@ -12,8 +12,8 @@
```ts
@CustomDialog
struct CustomDialogExample {
controller: CustomDialogController
struct CustomDialogExample1 {
controller: CustomDialogController | undefined
build() {
Column() {
Text('我是内容')
......@@ -27,21 +27,32 @@
3. 创建构造器,与装饰器呼应相连。
```ts
dialogController: CustomDialogController = new CustomDialogController({
builder: CustomDialogExample({}),
let bud:Record<string,string> = {}
let obj:object|undefined = undefined
dialogController: obj = new CustomDialogController({
builder: CustomDialogExample(bud),
})
```
4. 点击与onClick事件绑定的组件使弹窗弹出
```ts
Flex({justifyContent:FlexAlign.Center}){
Button('click me')
.onClick(() => {
this.dialogController.open()
})
}.width('100%')
```
```ts
class dialogc{
dialogController:CustomDialogController|undefined = undefined
open(){
if(this.dialogController){
this.dialogController.open()
}
}
}
Flex({justifyContent:FlexAlign.Center}){
Button('click me')
.onClick(() => {
let dia = new dialogc();
dia.open()
})
}.width('100%')
```
![zh-cn_image_0000001562700493](figures/zh-cn_image_0000001562700493.png)
......@@ -53,49 +64,57 @@
1.\@CustomDialog装饰器内添加按钮操作,同时添加数据函数的创建。
```ts
@CustomDialog
struct CustomDialogExample {
controller: CustomDialogController
cancel: () => void
confirm: () => void
build() {
Column() {
Text('我是内容').fontSize(20).margin({ top: 10, bottom: 10 })
Flex({ justifyContent: FlexAlign.SpaceAround }) {
Button('cancel')
.onClick(() => {
this.controller.close()
this.cancel()
}).backgroundColor(0xffffff).fontColor(Color.Black)
Button('confirm')
.onClick(() => {
this.controller.close()
this.confirm()
}).backgroundColor(0xffffff).fontColor(Color.Red)
}.margin({ bottom: 10 })
}
}
}
```
```ts
class cancelconfirmF{
cancel():void{}
confirm():void{}
}
@CustomDialog
struct CustomDialogExample {
controller: CustomDialogController | undefined
build() {
Column() {
Text('我是内容').fontSize(20).margin({ top: 10, bottom: 10 })
Flex({ justifyContent: FlexAlign.SpaceAround }) {
Button('cancel')
.onClick(() => {
if(this.controller){
this.controller.close()
}
let canf = new cancelconfirmF()
canf.cancel()
}).backgroundColor(0xffffff).fontColor(Color.Black)
Button('confirm')
.onClick(() => {
if(this.controller){
this.controller.close()
}
let conf = new cancelconfirmF()
conf.confirm()
}).backgroundColor(0xffffff).fontColor(Color.Red)
}.margin({ bottom: 10 })
}
}
}
```
2. 页面内需要在构造器内进行接收,同时创建相应的函数操作。
```ts
dialogController: CustomDialogController = new CustomDialogController({
builder: CustomDialogExample({
cancel: this.onCancel,
confirm: this.onAccept,
}),
alignment: DialogAlignment.Default, // 可设置dialog的对齐方式,设定显示在底部或中间等,默认为底部显示
})
onCancel() {
console.info('Callback when the first button is clicked')
}
onAccept() {
console.info('Callback when the second button is clicked')
}
```
```ts
dialogController: object = new CustomDialogController({
builder: CustomDialogExample({
cancel: this.onCancel,
confirm: this.onAccept,
}),
alignment: DialogAlignment.Default, // 可设置dialog的对齐方式,设定显示在底部或中间等,默认为底部显示
})
onCancel() {
console.info('Callback when the first button is clicked')
}
onAccept() {
console.info('Callback when the second button is clicked')
}
```
![zh-cn_image_0000001511421320](figures/zh-cn_image_0000001511421320.png)
......
......@@ -68,7 +68,8 @@ struct RadioExample {
.onChange((isChecked: boolean) => {
if(isChecked) {
// 切换为响铃模式
promptAction.showToast({ message: 'Ringing mode.' })
let st:Record<string,string> = {'message': 'Ringing mode.'}
promptAction.showToast(st)
}
})
Text('Ringing')
......@@ -80,7 +81,8 @@ struct RadioExample {
.onChange((isChecked: boolean) => {
if(isChecked) {
// 切换为振动模式
promptAction.showToast({ message: 'Vibration mode.' })
let st:Record<string,string> = {'message': 'Vibration mode.'}
promptAction.showToast(st)
}
})
Text('Vibration')
......@@ -92,7 +94,8 @@ struct RadioExample {
.onChange((isChecked: boolean) => {
if(isChecked) {
// 切换为静音模式
promptAction.showToast({ message: 'Silent mode.' })
let st:Record<string,string> = {'message': 'Silent mode.'}
promptAction.showToast(st)
}
})
Text('Silent')
......
......@@ -133,9 +133,11 @@ struct ToggleExample {
.margin({left: 200, right: 10})
.onChange((isOn: boolean) => {
if(isOn) {
promptAction.showToast({ message: 'Bluetooth is on.' })
let st:Record<string,string> = {'message': 'Bluetooth is on.'}
promptAction.showToast(st)
} else {
promptAction.showToast({ message: 'Bluetooth is off.' })
let st:Record<string,string> = {'message': 'Bluetooth is off.'}
promptAction.showToast(st)
}
})
}
......
......@@ -34,7 +34,7 @@ Video组件支持加载本地视频和网络视频。
```ts
@Component
export struct VideoPlayer{
private controller:VideoController;
private controller:VideoController | undefined;
private previewUris: Resource = $r ('app.media.preview');
private innerResource: Resource = $rawfile('videoTest.mp4');
build(){
......@@ -55,7 +55,7 @@ Video组件支持加载本地视频和网络视频。
```ts
@Component
export struct VideoPlayer{
private controller:VideoController;
private controller:VideoController | undefined;
private previewUris: Resource = $r ('app.media.preview');
private videosrc: string= 'dataability://device_id/com.domainname.dataability.videodata/video/10'
build(){
......@@ -77,7 +77,7 @@ Video组件支持加载本地视频和网络视频。
```ts
@Component
export struct VideoPlayer {
private controller: VideoController;
private controller: VideoController | undefined;
private videosrc: string = 'file:///data/storage/el2/base/haps/entry/files/show.mp4'
build() {
......@@ -100,7 +100,7 @@ export struct VideoPlayer {
```ts
@Component
export struct VideoPlayer{
private controller:VideoController;
private controller:VideoController | undefined;
private previewUris: Resource = $r ('app.media.preview');
private videosrc: string= 'https://www.example.com/example.mp4' // 使用时请替换为实际视频加载网址
build(){
......@@ -124,7 +124,7 @@ Video组件[属性](../reference/arkui-ts/ts-media-components-video.md#属性)
```ts
@Component
export struct VideoPlayer {
private controller: VideoController;
private controller: VideoController | undefined;
build() {
Column() {
......@@ -150,7 +150,7 @@ export struct VideoPlayer {
@Entry
@Component
struct VideoPlayer{
private controller:VideoController;
private controller:VideoController | undefined;
private previewUris: Resource = $r ('app.media.preview');
private innerResource: Resource = $rawfile('videoTest.mp4');
build(){
......@@ -213,7 +213,7 @@ Video控制器主要用于控制视频的状态,包括播放、暂停、停止
```ts
@Entry
@Component
struct VideoGuide {
struct VideoGuide1 {
@State videoSrc: Resource = $rawfile('videoTest.mp4')
@State previewUri: string = 'common/videoIcon.png'
@State curRate: PlaybackSpeed = PlaybackSpeed.Speed_Forward_1_00_X
......@@ -235,10 +235,14 @@ Video控制器主要用于控制视频的状态,包括播放、暂停、停止
controller: this.controller
}).controls(false).autoPlay(true)
.onPrepared((event)=>{
this.durationTime = event.duration
if(event){
this.durationTime = event.duration
}
})
.onUpdate((event)=>{
this.currentTime =event.time
if(event){
this.currentTime =event.time
}
})
Row() {
Text(JSON.stringify(this.currentTime) + 's')
......
......@@ -229,11 +229,19 @@ OpenHarmony上Camera、AVPlayer等符合生产者设计的部件都可以将数
```ts
class suf{
surfaceId:string = "";
mXComponentController: XComponentController = new XComponentController();
set(){
this.surfaceId = this.mXComponentController.getXComponentSurfaceId()
}
}
@State surfaceId:string = "";
mXComponentController: XComponentController = new XComponentController();
mXComponentController: object = new XComponentController();
XComponent({ id: '', type: 'surface', controller: this.mXComponentController })
.onLoad(() => {
this.surfaceId = this.mXComponentController.getXComponentSurfaceId()
let sufset = new suf()
sufset.set()
})
```
......
......@@ -70,8 +70,10 @@ struct MouseExample {
Button(this.isHovered ? 'Hovered!' : 'Not Hover')
.width(200).height(100)
.backgroundColor(this.isHovered ? Color.Green : Color.Gray)
.onHover((isHover: boolean) => { // 使用onHover接口监听鼠标是否悬浮在Button组件上
this.isHovered = isHover;
.onHover((isHover?: boolean) => { // 使用onHover接口监听鼠标是否悬浮在Button组件上
if(isHover){
this.isHovered = isHover;
}
})
}.width('100%').height('100%').justifyContent(FlexAlign.Center)
}
......@@ -126,15 +128,19 @@ struct MouseExample {
.width(200)
.height(100)
.backgroundColor(this.isHovered ? Color.Green : Color.Gray)
.onHover((isHover: boolean) => {
this.isHovered = isHover
.onHover((isHover?: boolean) => {
if(isHover){
this.isHovered = isHover
}
})
.onMouse((event: MouseEvent) => { // 给Button组件设置onMouse回调
this.buttonText = 'Button onMouse:\n' + '' +
'button = ' + event.button + '\n' +
'action = ' + event.action + '\n' +
'x,y = (' + event.x + ',' + event.y + ')' + '\n' +
'windowXY=(' + event.windowX + ',' + event.windowY + ')';
.onMouse((event?: MouseEvent) => { // 设置Button的onMouse回调
if(event){
this.buttonText = 'Button onMouse:\n' + '' +
'button = ' + event.button + '\n' +
'action = ' + event.action + '\n' +
'x,y = (' + event.x + ',' + event.y + ')' + '\n' +
'windowXY=(' + event.windowX + ',' + event.windowY + ')';
}
})
Divider()
Text(this.buttonText).fontColor(Color.Green)
......@@ -146,12 +152,14 @@ struct MouseExample {
.justifyContent(FlexAlign.Center)
.borderWidth(2)
.borderColor(Color.Red)
.onMouse((event: MouseEvent) => { // 给Column组件设置onMouse回调
this.columnText = 'Column onMouse:\n' + '' +
'button = ' + event.button + '\n' +
'action = ' + event.action + '\n' +
'x,y = (' + event.x + ',' + event.y + ')' + '\n' +
'windowXY=(' + event.windowX + ',' + event.windowY + ')';
.onMouse((event?: MouseEvent) => { // Set the onMouse callback for the column.
if(event){
this.columnText = 'Column onMouse:\n' + '' +
'button = ' + event.button + '\n' +
'action = ' + event.action + '\n' +
'x,y = (' + event.x + ',' + event.y + ')' + '\n' +
'windowXY=(' + event.windowX + ',' + event.windowY + ')';
}
})
}
}
......@@ -177,20 +185,40 @@ struct MouseExample {
```ts
class ish{
isHovered:boolean = false
set(val:boolean){
this.isHovered = val;
}
}
class butf{
buttonText:string = ''
set(val:string){
this.buttonText = val
}
}
Button(this.isHovered ? 'Hovered!' : 'Not Hover')
.width(200)
.height(100)
.backgroundColor(this.isHovered ? Color.Green : Color.Gray)
.onHover((isHover: boolean) => {
this.isHovered = isHover;
.onHover((isHover?: boolean) => {
if(isHover){
let ishset = new ish()
ishset.set(isHover)
}
})
.onMouse((event: MouseEvent) => {
event.stopPropagation(); // 在Button的onMouse事件中设置阻止冒泡
this.buttonText = 'Button onMouse:\n' + '' +
'button = ' + event.button + '\n' +
'action = ' + event.action + '\n' +
'x,y = (' + event.x + ',' + event.y + ')' + '\n' +
'windowXY=(' + event.windowX + ',' + event.windowY + ')';
.onMouse((event?: MouseEvent) => {
if(event){
if(event.stopPropagation){
event.stopPropagation(); // 在Button的onMouse事件中设置阻止冒泡
}
let butset = new butf()
butset.set('Button onMouse:\n' + '' +
'button = ' + event.button + '\n' +
'action = ' + event.action + '\n' +
'x,y = (' + event.x + ',' + event.y + ')' + '\n' +
'windowXY=(' + event.windowX + ',' + event.windowY + ')');
}
})
```
......@@ -298,17 +326,19 @@ struct KeyEventExample {
Column() {
Button('onKeyEvent')
.width(140).height(70)
.onKeyEvent((event: KeyEvent) => { // 给Button设置onKeyEvent事件
if (event.type === KeyType.Down) {
this.buttonType = 'Down';
}
if (event.type === KeyType.Up) {
this.buttonType = 'Up';
.onKeyEvent((event?: KeyEvent) => { // 给Button设置onKeyEvent事件
if(event){
if (event.type === KeyType.Down) {
this.buttonType = 'Down';
}
if (event.type === KeyType.Up) {
this.buttonType = 'Up';
}
this.buttonText = 'Button: \n' +
'KeyType:' + this.buttonType + '\n' +
'KeyCode:' + event.keyCode + '\n' +
'KeyText:' + event.keyText;
}
this.buttonText = 'Button: \n' +
'KeyType:' + this.buttonType + '\n' +
'KeyCode:' + event.keyCode + '\n' +
'KeyText:' + event.keyText;
})
Divider()
......@@ -317,17 +347,19 @@ struct KeyEventExample {
Divider()
Text(this.columnText).fontColor(Color.Red)
}.width('100%').height('100%').justifyContent(FlexAlign.Center)
.onKeyEvent((event: KeyEvent) => { // 给父组件Column设置onKeyEvent事件
if (event.type === KeyType.Down) {
this.columnType = 'Down';
}
if (event.type === KeyType.Up) {
this.columnType = 'Up';
.onKeyEvent((event?: KeyEvent) => { // 给父组件Column设置onKeyEvent事件
if(event){
if (event.type === KeyType.Down) {
this.columnType = 'Down';
}
if (event.type === KeyType.Up) {
this.columnType = 'Up';
}
this.columnText = 'Column: \n' +
'KeyType:' + this.buttonType + '\n' +
'KeyCode:' + event.keyCode + '\n' +
'KeyText:' + event.keyText;
}
this.columnText = 'Column: \n' +
'KeyType:' + this.buttonType + '\n' +
'KeyCode:' + event.keyCode + '\n' +
'KeyText:' + event.keyText;
})
}
}
......@@ -353,21 +385,36 @@ struct KeyEventExample {
```ts
class butypef{
buttonType:string = ''
set(val:string){
this.buttonType = val
}
get(){
return this.buttonType
}
}
Button('onKeyEvent')
.width(140).height(70)
.onKeyEvent((event: KeyEvent) => {
.onKeyEvent((event?: KeyEvent|object) => {
// 通过stopPropagation阻止事件冒泡
event.stopPropagation();
if (event.type === KeyType.Down) {
this.buttonType = 'Down';
}
if (event.type === KeyType.Up) {
this.buttonType = 'Up';
if(event){
event.stopPropagation();
if (event.type === KeyType.Down) {
let butset = new butypef()
butset.set('Down')
}
if (event.type === KeyType.Up) {
let butset = new butypef()
butset.set('Up')
}
let butfset = new butf()
let butset = new butypef()
butfset.set('Button: \n' +
'KeyType:' + butset.get() + '\n' +
'KeyCode:' + event.keyCode + '\n' +
'KeyText:' + event.keyText)
}
this.buttonText = 'Button: \n' +
'KeyType:' + this.buttonType + '\n' +
'KeyCode:' + event.keyCode + '\n' +
'KeyText:' + event.keyText;
})
```
......
......@@ -75,6 +75,8 @@
```ts
import List from '@ohos.util.List';
import promptAction from '@ohos.promptAction';
onFocus(event: () => void)
```
......@@ -345,8 +347,10 @@ struct FocusableExample {
Divider()
}.width('100%').justifyContent(FlexAlign.Center)
.onKeyEvent((e) => { // 绑定onKeyEvent,在该Column组件获焦时,按下'F'键,可将第二个Text的focusable置反
if (e.keyCode === 2022 && e.type === KeyType.Down) {
this.textFocusable = !this.textFocusable;
if(e){
if (e.keyCode === 2022 && e.type === KeyType.Down) {
this.textFocusable = !this.textFocusable;
}
}
})
}
......@@ -401,7 +405,7 @@ import promptAction from '@ohos.promptAction';
class MyDataSource implements IDataSource {
private list: number[] = [];
private listener: DataChangeListener;
private listener: DataChangeListener|undefined = undefined;
constructor(list: number[]) {
this.list = list;
......@@ -411,7 +415,7 @@ class MyDataSource implements IDataSource {
return this.list.length;
}
getData(index: number): any {
getData(index: number): object {
return this.list[index];
}
......@@ -423,16 +427,22 @@ class MyDataSource implements IDataSource {
}
}
class TmpM{
left:number = 20
bottom:number = 20
right:number = 20
}
let MarginTmp:TmpM = new TmpM()
@Entry
@Component
struct SwiperExample {
private swiperController: SwiperController = new SwiperController()
private data: MyDataSource = new MyDataSource([])
private swiperController: object = new SwiperController()
private data: object = new MyDataSource([])
aboutToAppear(): void {
let list = []
let list:number[] = []
for (let i = 1; i <= 4; i++) {
list.push(i.toString());
list.push(i);
}
this.data = new MyDataSource(list);
}
......@@ -507,7 +517,7 @@ struct SwiperExample {
.borderWidth(2)
.borderColor(Color.Gray)
.backgroundColor(Color.White)
}, item => item)
}, ((item:string):string => item))
}
.cachedCount(2)
.index(0)
......@@ -522,6 +532,18 @@ struct SwiperExample {
})
.margin({ left: 20, top: 20, right: 20 })
class swcf{
swiperController:SwiperController|undefined
fun(index:number){
if(this.swiperController){
if(index==0){
this.swiperController.showPrevious();
}else{
this.swiperController.showNext();
}
}
}
}
Row({ space: 40 }) {
Button('')
.fontSize(40)
......@@ -529,7 +551,8 @@ struct SwiperExample {
.fontColor(Color.Black)
.backgroundColor(Color.Transparent)
.onClick(() => {
this.swiperController.showPrevious();
let swf = new swcf()
swf.fun(0)
})
Button('')
.fontSize(40)
......@@ -537,7 +560,8 @@ struct SwiperExample {
.fontColor(Color.Black)
.backgroundColor(Color.Transparent)
.onClick(() => {
this.swiperController.showNext();
let swf = new swcf()
swf.fun(1)
})
}
.width(480)
......@@ -556,6 +580,7 @@ struct SwiperExample {
.height(50)
.backgroundColor('#dadbd9')
let tmp:Record<string,string> = {'message':'Button OK on clicked'}
Button('OK')
.fontSize(30)
.fontColor('#787878')
......@@ -564,7 +589,7 @@ struct SwiperExample {
.height(50)
.backgroundColor('#dadbd9')
.onClick(() => {
promptAction.showToast({ message: 'Button OK on clicked' });
promptAction.showToast(tmp);
})
}
.width(480)
......@@ -573,7 +598,7 @@ struct SwiperExample {
.borderWidth(2)
.borderColor(Color.Gray)
.backgroundColor('#dff2e4')
.margin({ left: 20, bottom: 20, right: 20 })
.margin(MarginTmp)
}.backgroundColor('#f2f2f2')
.margin({ left: 50, top: 50, right: 20 })
}
......@@ -592,6 +617,8 @@ struct SwiperExample {
```ts
import promptAction from '@ohos.promptAction';
let Tmp:Record<string,string> = {'message':'Button OK on clicked'}
Button('OK')
.defaultFocus(true) // 设置Button-OK为defaultFocus
.fontSize(30)
......@@ -599,7 +626,7 @@ Button('OK')
.type(ButtonType.Normal)
.width(140).height(50).backgroundColor('#dadbd9')
.onClick(() => {
promptAction.showToast({ message: 'Button OK on clicked' });
promptAction.showToast(Tmp);
})
```
......@@ -646,13 +673,22 @@ tabIndex用于设置自定义TAB键走焦顺序,默认值为0。使用“TAB/S
```ts
class swcf{
swiperController:SwiperController|undefined
fun(){
if(this.swiperController){
this.swiperController.showPrevious();
}
}
}
Button('')
.fontSize(40)
.fontWeight(FontWeight.Bold)
.fontColor(Color.Black)
.backgroundColor(Color.Transparent)
.onClick(() => {
this.swiperController.showPrevious();
let swf = new swcf()
swf.fun()
})
.tabIndex(2) // Button-左箭头设置为第二个tabIndex节点
```
......@@ -660,13 +696,15 @@ tabIndex用于设置自定义TAB键走焦顺序,默认值为0。使用“TAB/S
```ts
import promptAction from '@ohos.promptAction';
let Tmp:Record<string,string> = {'message':'Button OK on clicked'}
Button('OK')
.fontSize(30)
.fontColor('#787878')
.type(ButtonType.Normal)
.width(140).height(50).backgroundColor('#dadbd9')
.onClick(() => {
promptAction.showToast({ message: 'Button OK on clicked' });
promptAction.showToast(Tmp);
})
.tabIndex(3) // Button-OK设置为第三个tabIndex节点
```
......@@ -707,7 +745,7 @@ import promptAction from '@ohos.promptAction';
class MyDataSource implements IDataSource {
private list: number[] = [];
private listener: DataChangeListener;
private listener: DataChangeListener|undefined = undefined;
constructor(list: number[]) {
this.list = list;
......@@ -717,7 +755,7 @@ class MyDataSource implements IDataSource {
return this.list.length;
}
getData(index: number): any {
getData(index: number): number[] {
return this.list[index];
}
......@@ -736,9 +774,9 @@ struct SwiperExample {
private data: MyDataSource = new MyDataSource([])
aboutToAppear(): void {
let list = []
let list: number[] = []
for (let i = 1; i <= 4; i++) {
list.push(i.toString());
list.push(i);
}
this.data = new MyDataSource(list);
}
......@@ -815,7 +853,7 @@ struct SwiperExample {
.borderColor(Color.Gray)
.backgroundColor(Color.White)
.tabIndex(1)
}, item => item)
}, ((item:string):string => item))
}
.cachedCount(2)
.index(0)
......@@ -866,6 +904,7 @@ struct SwiperExample {
.height(50)
.backgroundColor('#dadbd9')
let tmp:Record<string,string> = {'message':'Button OK on clicked'}
Button('OK')
.fontSize(30)
.fontColor('#787878')
......@@ -875,7 +914,7 @@ struct SwiperExample {
.backgroundColor('#dadbd9')
.defaultFocus(true)
.onClick(() => {
promptAction.showToast({ message: 'Button OK on clicked' });
promptAction.showToast(tmp);
})
.groupDefaultFocus(true) // 设置Button-OK为第三个tabIndex节点的默认焦点
}
......@@ -1017,21 +1056,25 @@ struct RequestFocusExample {
}
}.width('100%').margin({ top:20 })
.onKeyEvent((e) => {
if (e.keyCode >= 2017 && e.keyCode <= 2022) {
this.requestId = e.keyCode - 2017;
} else if (e.keyCode === 2030) {
this.requestId = 6;
} else {
return;
}
if (e.type !== KeyType.Down) {
return;
if(e){
if (e.keyCode >= 2017 && e.keyCode <= 2022) {
this.requestId = e.keyCode - 2017;
} else if (e.keyCode === 2030) {
this.requestId = 6;
} else {
return;
}
if (e.type !== KeyType.Down) {
return;
}
}
let res = focusControl.requestFocus(this.idList[this.requestId]);
let tmps:Record<string,string> = {'message':'Request success'}
let tmpf:Record<string,string> = {'message':'Request failed'}
if (res) {
promptAction.showToast({message: 'Request success'});
promptAction.showToast(tmps);
} else {
promptAction.showToast({message: 'Request failed'});
promptAction.showToast(tmpf);
}
})
}
......
......@@ -88,7 +88,7 @@ import image from '@ohos.multimedia.image';
@Component
struct Index {
@State visible: Visibility = Visibility.Visible
private pixelMapReader = undefined
private pixelMapReader:object|undefined = undefined
aboutToAppear() {
console.info('begin to create pixmap has info message: ')
......@@ -97,21 +97,28 @@ struct Index {
createPixelMap() {
let color = new ArrayBuffer(4 * 96 * 96);
var buffer = new Uint8Array(color);
for (var i = 0; i < buffer.length; i++) {
let buffer = new Uint8Array(color);
for (let i = 0; i < buffer.length; i++) {
buffer[i] = (i + 1) % 255;
}
let opts = {
alphaType: 0,
editable: true,
pixelFormat: 4,
scaleMode: 1,
size: { height: 96, width: 96 }
class hw{
height:number = 96
width:number = 96
}
const promise = image.createPixelMap(color, opts);
promise.then((data) => {
let hwo:hw = new hw()
let opts:Record<string,number|boolean|hw> = {
'alphaType': 0,
'editable': true,
'pixelFormat': 4,
'scaleMode': 1,
'size': hwo
}
const promise:image = image.createPixelMap(color, opts);
promise.then((data:object|undefined) => {
console.info('create pixmap has info message: ' + JSON.stringify(data))
this.pixelMapReader = data;
if(data){
this.pixelMapReader = data;
}
})
}
......@@ -148,7 +155,7 @@ struct Index {
console.info('Text onDrag start')
return { pixelMap: this.pixelMapReader, extraInfo: 'custom extra info.' }
})
.onDrop((event: DragEvent, extraParams: string) => {
.onDrop((event: DragEvent|undefined, extraParams: string|undefined) => {
console.info('Text onDragDrop, ')
this.visible = Visibility.None //拖动结束后,使源不可见
})
......@@ -190,7 +197,7 @@ struct Index {
.visibility(Visibility.Visible)
List({ space: 20, initialIndex: 0 }) {
ForEach(this.number, (item) => {
ForEach(this.number, (item:string) => {
ListItem() {
Text('' + item)
.width('100%')
......@@ -200,7 +207,7 @@ struct Index {
.textAlign(TextAlign.Center)
.backgroundColor(0xFFFFFF)
}
}, item => item)
}, ((item:string):string => item))
ListItem() {
Text('Across Window Drag This')
......@@ -217,16 +224,16 @@ struct Index {
.width('90%')
.border({ width: 1 })
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 })
.onDragEnter((event: DragEvent, extraParams: string) => { //拖拽进去组件
.onDragEnter((event: DragEvent|undefined, extraParams: string|undefined) => { //拖拽进去组件
console.info('List onDragEnter, ' + extraParams)
})
.onDragMove((event: DragEvent, extraParams: string) => { //拖拽时移动
.onDragMove((event: DragEvent|undefined, extraParams: string|undefined) => { //拖拽时移动
console.info('List onDragMove, ' + extraParams)
})
.onDragLeave((event: DragEvent, extraParams: string) => { //拖拽离开组件
.onDragLeave((event: DragEvent|undefined, extraParams: string|undefined) => { //拖拽离开组件
console.info('List onDragLeave, ' + extraParams)
})
.onDrop((event: DragEvent, extraParams: string) => { //释放组件
.onDrop((event: DragEvent|undefined, extraParams: string|undefined) => { //释放组件
console.info('List onDragDrop, ' + extraParams)
this.visible2 = Visibility.Visible //拖拽完成使拖入目标可见
})
......@@ -267,36 +274,40 @@ struct TouchExample {
build() {
Column() {
Button('Touch').height(40).width(100)
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) {
this.eventType = 'Down';
}
if (event.type === TouchType.Up) {
this.eventType = 'Up';
.onTouch((event?: TouchEvent) => {
if(event){
if (event.type === TouchType.Down) {
this.eventType = 'Down';
}
if (event.type === TouchType.Up) {
this.eventType = 'Up';
}
if (event.type === TouchType.Move) {
this.eventType = 'Move';
}
this.text = 'TouchType:' + this.eventType + '\nDistance between touch point and touch element:\nx: '
+ event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:('
+ event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:'
+ event.target.area.width + '\nheight:' + event.target.area.height
}
if (event.type === TouchType.Move) {
this.eventType = 'Move';
}
this.text = 'TouchType:' + this.eventType + '\nDistance between touch point and touch element:\nx: '
+ event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:('
+ event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:'
+ event.target.area.width + '\nheight:' + event.target.area.height
})
Button('Touch').height(50).width(200).margin(20)
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) {
this.eventType = 'Down';
}
if (event.type === TouchType.Up) {
this.eventType = 'Up';
}
if (event.type === TouchType.Move) {
this.eventType = 'Move';
.onTouch((event?: TouchEvent) => {
if(event){
if (event.type === TouchType.Down) {
this.eventType = 'Down';
}
if (event.type === TouchType.Up) {
this.eventType = 'Up';
}
if (event.type === TouchType.Move) {
this.eventType = 'Move';
}
this.text = 'TouchType:' + this.eventType + '\nDistance between touch point and touch element:\nx: '
+ event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:('
+ event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:'
+ event.target.area.width + '\nheight:' + event.target.area.height
}
this.text = 'TouchType:' + this.eventType + '\nDistance between touch point and touch element:\nx: '
+ event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:('
+ event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:'
+ event.target.area.width + '\nheight:' + event.target.area.height
})
Text(this.text)
}.width('100%').padding(30)
......
......@@ -64,18 +64,21 @@ import curves from '@ohos.curves';
import window from '@ohos.window';
import display from '@ohos.display';
import mediaquery from '@ohos.mediaquery';
export class GlobalContext {
static mainWin: window.Window|undefined = undefined;
static mainWindowSize:window.Size|undefined = undefined;
}
/**
* 窗口、屏幕相关信息管理类
*/
export class WindowManager {
private static instance: WindowManager = null;
private displayInfo: display.Display = null;
private static instance: WindowManager|null = null;
private displayInfo: display.Display|null = null;
private orientationListener = mediaquery.matchMediaSync('(orientation: landscape)');
private portraitFunc = null;
private portraitFunc: Function | null = null;
constructor() {
this.portraitFunc = this.onPortrait.bind(this);
this.portraitFunc = (mediaQueryResult: mediaquery.MediaQueryResult) => { this.onPortrait(mediaQueryResult) };
this.orientationListener.on('change', this.portraitFunc)
this.loadDisplayInfo()
}
......@@ -88,30 +91,30 @@ export class WindowManager {
if (win == null) {
return
}
globalThis.mainWin = win;
GlobalContext.mainWin = win;
win.on("windowSizeChange", (data: window.Size) => {
if (globalThis.mainWindowSize == undefined || globalThis.mainWindowSize == null) {
globalThis.mainWindowSize = data;
if (GlobalContext.mainWindowSize == undefined || GlobalContext.mainWindowSize == null) {
GlobalContext.mainWindowSize = data;
} else {
if (globalThis.mainWindowSize.width == data.width && globalThis.mainWindowSize.height == data.height) {
if (GlobalContext.mainWindowSize.width == data.width && GlobalContext.mainWindowSize.height == data.height) {
return
}
globalThis.mainWindowSize = data;
GlobalContext.mainWindowSize = data;
}
let winWidth = this.getMainWindowWidth();
AppStorage.SetOrCreate<number>('mainWinWidth', winWidth)
let winHeight = this.getMainWindowHeight();
AppStorage.SetOrCreate<number>('mainWinHeight', winHeight)
globalThis.context.eventHub.emit("windowSizeChange", winWidth, winHeight)
GlobalContext.context.eventHub.emit("windowSizeChange", winWidth, winHeight)
})
}
static getInstance(): WindowManager {
if (this.instance == null) {
this.instance = new WindowManager();
if (WindowManager.instance == null) {
WindowManager.instance = new WindowManager();
}
return this.instance
return WindowManager.instance
}
private onPortrait(mediaQueryResult: mediaquery.MediaQueryResult) {
......@@ -127,8 +130,8 @@ export class WindowManager {
* @param ori 常量枚举值:window.Orientation
*/
changeOrientation(ori: window.Orientation) {
if (globalThis.mainWin != null) {
globalThis.mainWin.setPreferredOrientation(ori)
if (GlobalContext.mainWin != null) {
GlobalContext.mainWin.setPreferredOrientation(ori)
}
}
......@@ -142,14 +145,14 @@ export class WindowManager {
* 获取main窗口宽度,单位vp
*/
getMainWindowWidth(): number {
return globalThis.mainWindowSize != null ? px2vp(globalThis.mainWindowSize.width) : 0
return GlobalContext.mainWindowSize != null ? px2vp(GlobalContext.mainWindowSize.width) : 0
}
/**
* 获取main窗口高度,单位vp
*/
getMainWindowHeight(): number {
return globalThis.mainWindowSize != null ? px2vp(globalThis.mainWindowSize.height) : 0
return GlobalContext.mainWindowSize != null ? px2vp(GlobalContext.mainWindowSize.height) : 0
}
/**
......@@ -173,8 +176,8 @@ export class WindowManager {
if (this.orientationListener) {
this.orientationListener.off('change', this.portraitFunc)
}
if (globalThis.mainWin != null) {
globalThis.mainWin.off('windowSizeChange')
if (GlobalContext.mainWin != null) {
GlobalContext.mainWin.off('windowSizeChange')
}
WindowManager.instance = null;
}
......@@ -232,7 +235,7 @@ export struct TaskSwitchMainPage {
@State taskViewOffsetX: number = 0;
@State cardOffset: number = this.displayWidth / 4;
lastCardOffset: number = this.cardOffset;
startTime: number
startTime: number|undefined=undefined
// 每个卡片初始位置
aboutToAppear() {
......@@ -258,28 +261,30 @@ export struct TaskSwitchMainPage {
// 滑动组件
Scroll(this.scroller) {
Row({ space: this.cardSpace }) {
ForEach(taskDataArr, (item, index) => {
Column()
.width(this.cardWidth)
.height(this.cardHeight)
.backgroundColor(item.bgColor)
.borderStyle(BorderStyle.Solid)
.borderWidth(1)
.borderColor(0xAFEEEE)
.borderRadius(15)
// 计算子组件的仿射属性
.scale((this.getProgress(index) >= 0.4 && this.getProgress(index) <= 0.6) ?
{
x: 1.1 - Math.abs(0.5 - this.getProgress(index)),
y: 1.1 - Math.abs(0.5 - this.getProgress(index))
} :
{ x: 1, y: 1 })
.animation({ curve: Curve.Smooth })
// 滑动动画
.translate({ x: this.cardOffset })
.animation({ curve: curves.springMotion() })
.zIndex((this.getProgress(index) >= 0.4 && this.getProgress(index) <= 0.6) ? 2 : 1)
}, item => item.index)
ForEach(taskDataArr, (item:TaskData, index:number|undefined) => {
if(index){
Column()
.width(this.cardWidth)
.height(this.cardHeight)
.backgroundColor(item.bgColor)
.borderStyle(BorderStyle.Solid)
.borderWidth(1)
.borderColor(0xAFEEEE)
.borderRadius(15)
// 计算子组件的仿射属性
.scale((this.getProgress(index) >= 0.4 && this.getProgress(index) <= 0.6) ?
{
x: 1.1 - Math.abs(0.5 - this.getProgress(index)),
y: 1.1 - Math.abs(0.5 - this.getProgress(index))
} :
{ x: 1, y: 1 })
.animation({ curve: Curve.Smooth })
// 滑动动画
.translate({ x: this.cardOffset })
.animation({ curve: curves.springMotion() })
.zIndex((this.getProgress(index) >= 0.4 && this.getProgress(index) <= 0.6) ? 2 : 1)
}
}, ((item:string):string => item))
}
.width((this.cardWidth + this.cardSpace) * (taskDataArr.length + 1))
.height('100%')
......@@ -287,41 +292,49 @@ export struct TaskSwitchMainPage {
.gesture(
GestureGroup(GestureMode.Parallel,
PanGesture({ direction: PanDirection.Horizontal, distance: 5 })
.onActionStart((event: GestureEvent) => {
this.startTime = event.timestamp;
})
.onActionUpdate((event: GestureEvent) => {
this.cardOffset = this.lastCardOffset + event.offsetX;
})
.onActionEnd((event: GestureEvent) => {
let time = event.timestamp - this.startTime;
let speed = event.offsetX / (time / 1000000000);
let moveX = Math.pow(speed, 2) / 7000 * (speed > 0 ? 1 : -1);
this.cardOffset += moveX;
// 左滑大于最右侧位置
let cardOffsetMax = -(taskDataArr.length - 1) * (this.displayWidth / 2);
if (this.cardOffset < cardOffsetMax) {
this.cardOffset = cardOffsetMax;
}
// 右滑大于最左侧位置
if (this.cardOffset > this.displayWidth / 4) {
this.cardOffset = this.displayWidth / 4;
.onActionStart((event: GestureEvent|undefined) => {
if(event){
this.startTime = event.timestamp;
}
// 左右滑动距离不满足/满足切换关系时,补位/退回
let remainMargin = this.cardOffset % (this.displayWidth / 2);
if (remainMargin < 0) {
remainMargin = this.cardOffset % (this.displayWidth / 2) + this.displayWidth / 2;
})
.onActionUpdate((event: GestureEvent|undefined) => {
if(event){
this.cardOffset = this.lastCardOffset + event.offsetX;
}
if (remainMargin <= this.displayWidth / 4) {
this.cardOffset += this.displayWidth / 4 - remainMargin;
} else {
this.cardOffset -= this.displayWidth / 4 - (this.displayWidth / 2 - remainMargin);
})
.onActionEnd((event: GestureEvent|undefined) => {
if(event){
if(this.startTime){
let time = event.timestamp - this.startTime;
}
let speed = event.offsetX / (time / 1000000000);
let moveX = Math.pow(speed, 2) / 7000 * (speed > 0 ? 1 : -1);
this.cardOffset += moveX;
// 左滑大于最右侧位置
let cardOffsetMax = -(taskDataArr.length - 1) * (this.displayWidth / 2);
if (this.cardOffset < cardOffsetMax) {
this.cardOffset = cardOffsetMax;
}
// 右滑大于最左侧位置
if (this.cardOffset > this.displayWidth / 4) {
this.cardOffset = this.displayWidth / 4;
}
// 左右滑动距离不满足/满足切换关系时,补位/退回
let remainMargin = this.cardOffset % (this.displayWidth / 2);
if (remainMargin < 0) {
remainMargin = this.cardOffset % (this.displayWidth / 2) + this.displayWidth / 2;
}
if (remainMargin <= this.displayWidth / 4) {
this.cardOffset += this.displayWidth / 4 - remainMargin;
} else {
this.cardOffset -= this.displayWidth / 4 - (this.displayWidth / 2 - remainMargin);
}
// 记录本次滑动偏移量
this.lastCardOffset = this.cardOffset;
}
// 记录本次滑动偏移量
this.lastCardOffset = this.cardOffset;
})
), GestureMask.IgnoreInternal)
.scrollable(ScrollDirection.Horizontal)
......
......@@ -54,7 +54,7 @@ class PointClass extends Array<number> {
}
add(rhs: PointClass): PointClass {
let result = new Array<number>() as Point;
let result: Point = new Array<number>() as Point;
for (let i = 0; i < 2; i++) {
result.push(rhs[i] + this[i])
}
......@@ -62,7 +62,7 @@ class PointClass extends Array<number> {
}
subtract(rhs: PointClass): PointClass {
let result = new Array<number>() as Point;
let result: Point = new Array<number>() as Point;
for (let i = 0; i < 2; i++) {
result.push(this[i] - rhs[i]);
}
......@@ -70,7 +70,7 @@ class PointClass extends Array<number> {
}
multiply(scale: number): PointClass {
let result = new Array<number>() as Point;
let result: Point = new Array<number>() as Point;
for (let i = 0; i < 2; i++) {
result.push(this[i] * scale)
}
......@@ -84,7 +84,7 @@ class PointVector extends Array<PointClass> implements AnimatableArithmetic<Arra
constructor(initialValue: Array<Point>) {
super();
if (initialValue.length) {
initialValue.forEach(p => this.push(new PointClass(p)))
initialValue.forEach((p:object) => this.push(new PointClass(p)))
}
}
......@@ -128,7 +128,7 @@ class PointVector extends Array<PointClass> implements AnimatableArithmetic<Arra
}
}
function randomInt(min, max) {
function randomInt(min:number, max:number) {
return Math.floor(Math.random() * (max - min) + min);
}
......
......@@ -63,7 +63,7 @@ Canvas提供画布组件,用于自定义绘制图形,开发者使用CanvasRe
.height('100%')
.backgroundColor('#F5DC62')
.onReady(() =>{
var offContext = this.offCanvas.getContext("2d", this.settings)
let offContext = this.offCanvas.getContext("2d", this.settings)
//可以在这里绘制内容
offContext.strokeRect(50, 50, 200, 150);
//将离屏绘值渲染的图像在普通画布上显示
......@@ -98,13 +98,18 @@ Canvas提供画布组件,用于自定义绘制图形,开发者使用CanvasRe
onReady(event: () =&gt; void)是Canvas组件初始化完成时的事件回调,调用该事件后,可获取Canvas组件的确定宽高,进一步使用CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象调用相关API进行图形绘制。
```ts
class Contextset{
settings: RenderingContextSettings = new RenderingContextSettings(true)
context: CanvasRenderingContext2D= new CanvasRenderingContext2D(this.settings)
}
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#F5DC62')
.onReady(() => {
this.context.fillStyle = '#0097D4';
this.context.fillRect(50, 50, 100, 100);
let con:Contextset = new Contextset()
con.context.fillStyle = '#0097D4';
con.context.fillRect(50, 50, 100, 100);
})
```
......@@ -119,15 +124,20 @@ Canvas(this.context)
- 通过CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象直接调用相关API进行绘制。
```ts
class Contextset{
settings: RenderingContextSettings = new RenderingContextSettings(true)
context: CanvasRenderingContext2D= new CanvasRenderingContext2D(this.settings)
}
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#F5DC62')
.onReady(() =>{
this.context.beginPath();
this.context.moveTo(50, 50);
this.context.lineTo(280, 160);
this.context.stroke();
let con:Contextset = new Contextset()
con.context.beginPath();
con.context.moveTo(50, 50);
con.context.lineTo(280, 160);
con.context.stroke();
})
```
......@@ -136,14 +146,19 @@ Canvas(this.context)
- 先单独定义path2d对象构造理想的路径,再通过调用CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象的stroke接口或者fill接口进行绘制,具体使用可以参考[Path2D对象](../reference/arkui-ts/ts-components-canvas-path2d.md)
```ts
class Contextset{
settings: RenderingContextSettings = new RenderingContextSettings(true)
context: CanvasRenderingContext2D= new CanvasRenderingContext2D(this.settings)
}
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#F5DC62')
.onReady(() =>{
let con:Contextset = new Contextset()
let region = new Path2D();
region.arc(100, 75, 50, 0, 6.28);
this.context.stroke(region);
con.context.stroke(region);
})
```
......@@ -158,23 +173,28 @@ OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供
可以通过[arc](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#arc)(绘制弧线路径)、 [ellipse](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#ellipse)(绘制一个椭圆)、[rect](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#rect)(创建矩形路径)等接口绘制基础形状。
```ts
class Contextset{
settings: RenderingContextSettings = new RenderingContextSettings(true)
context: CanvasRenderingContext2D= new CanvasRenderingContext2D(this.settings)
}
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#F5DC62')
.onReady(() =>{
let con:Contextset = new Contextset()
//绘制矩形
this.context.beginPath();
this.context.rect(100, 50, 100, 100);
this.context.stroke();
con.context.beginPath();
con.context.rect(100, 50, 100, 100);
con.context.stroke();
//绘制圆形
this.context.beginPath();
this.context.arc(150, 250, 50, 0, 6.28);
this.context.stroke();
con.context.beginPath();
con.context.arc(150, 250, 50, 0, 6.28);
con.context.stroke();
//绘制椭圆
this.context.beginPath();
this.context.ellipse(150, 450, 50, 100, Math.PI * 0.25, Math.PI * 0, Math.PI * 2);
this.context.stroke();
con.context.beginPath();
con.context.ellipse(150, 450, 50, 100, Math.PI * 0.25, Math.PI * 0, Math.PI * 2);
con.context.stroke();
})
```
......@@ -186,17 +206,22 @@ OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供
可以通过[fillText](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#filltext)(绘制填充类文本)、[strokeText](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#stroketext)(绘制描边类文本)等接口进行文本绘制。
```ts
class Contextset{
settings: RenderingContextSettings = new RenderingContextSettings(true)
context: CanvasRenderingContext2D= new CanvasRenderingContext2D(this.settings)
}
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#F5DC62')
.onReady(() =>{
let con:Contextset = new Contextset()
//绘制填充类文本
this.context.font = '50px sans-serif';
this.context.fillText("Hello World!", 50, 100);
con.context.font = '50px sans-serif';
con.context.fillText("Hello World!", 50, 100);
//绘制描边类文本
this.context.font = '55px sans-serif';
this.context.strokeText("Hello World!", 50, 150);
con.context.font = '55px sans-serif';
con.context.strokeText("Hello World!", 50, 150);
})
```
......@@ -222,7 +247,7 @@ OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供
.height('100%')
.backgroundColor('#F5DC62')
.onReady(() =>{
var offContext = this.offCanvas.getContext("2d", this.settings)
let offContext = this.offCanvas.getContext("2d", this.settings)
// 使用drawImage接口将图片画在(0,0)为起点,宽高130的区域
offContext.drawImage(this.img,0,0,130,130);
// 使用getImageData接口,获得canvas组件区域中,(50,50)为起点,宽高130范围内的绘制内容
......@@ -247,20 +272,27 @@ OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供
Canvas中还提供其他类型的方法。渐变([CanvasGradient对象](../reference/arkui-ts/ts-components-canvas-canvasgradient.md))相关的方法:[createLinearGradient](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#createlineargradient)(创建一个线性渐变色)、[createRadialGradient](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#createradialgradient)(创建一个径向渐变色)等。
```ts
class Contextset{
settings: RenderingContextSettings = new RenderingContextSettings(true)
context: CanvasRenderingContext2D= new CanvasRenderingContext2D(this.settings)
}
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#F5DC62')
.onReady(() =>{
let con:Contextset = new Contextset()
//创建一个径向渐变色的CanvasGradient对象
let grad = this.context.createRadialGradient(200,200,50, 200,200,200)
let grad:CanvasRenderingContext2D|undefined = con.context.createRadialGradient(200,200,50, 200,200,200)
//为CanvasGradient对象设置渐变断点值,包括偏移和颜色
grad.addColorStop(0.0, '#E87361');
grad.addColorStop(0.5, '#FFFFF0');
grad.addColorStop(1.0, '#BDDB69');
if(grad){
grad.addColorStop(0.0, '#E87361');
grad.addColorStop(0.5, '#FFFFF0');
grad.addColorStop(1.0, '#BDDB69');
con.context.fillStyle = grad;
}
//用CanvasGradient对象填充矩形
this.context.fillStyle = grad;
this.context.fillRect(0, 0, 400, 400);
con.context.fillRect(0, 0, 400, 400);
})
```
......
......@@ -25,7 +25,7 @@
```ts
// 出现时会是所有转场效果的出现效果叠加,消失时会是所有消失转场效果的叠加
// 用于说明各个effect跟随的动画参数
private effect: TransitionEffect =
private effect: object =
TransitionEffect.OPACITY // 创建了透明度转场效果,这里没有调用animation接口,会跟随animateTo的动画参数
// 通过combine方法,添加缩放转场效果,并指定了springMotion(0.6, 1.2)曲线
.combine(TransitionEffect.scale({ x: 0, y: 0 }).animation({curve: curves.springMotion(0.6, 1.2) }))
......
......@@ -52,6 +52,20 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei
- 通过形状视口对图形进行放大与缩小。
```ts
class tmp{
x:number = 0
y:number = 0
width:number = 75
height:number = 75
}
let viep:tmp = new tmp()
class tmp1{
x:number = 0
y:number = 0
width:number = 300
height:number = 300
}
let viep1:tmp1 = new tmp1()
// 画一个宽高都为150的圆
Text('原始尺寸Circle组件')
Circle({width: 75, height: 75}).fill('#E87361')
......@@ -65,7 +79,7 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei
Rect().width('100%').height('100%').fill('#0097D4')
Circle({width: 75, height: 75}).fill('#E87361')
}
.viewPort({x: 0, y: 0, width: 75, height: 75})
.viewPort(viep)
.width(150)
.height(150)
.backgroundColor('#F5DC62')
......@@ -78,7 +92,7 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei
Rect().width('100%').height('100%').fill('#BDDB69')
Circle({width: 75, height: 75}).fill('#E87361')
}
.viewPort({x: 0, y: 0, width: 300, height: 300})
.viewPort(viep1)
.width(150)
.height(150)
.backgroundColor('#F5DC62')
......@@ -91,11 +105,25 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei
- 创建一个宽高都为300的shape组件,背景色为黄色,一个宽高都为300的viewport。用一个蓝色的矩形来填充viewport,在viewport中绘制一个半径为75的圆。
```ts
class tmp{
x:number = 0
y:number = 0
width:number = 300
height:number = 300
}
let viep:tmp = new tmp()
class tmp1{
x:number = -150
y:number = -150
width:number = 300
height:number = 300
}
let viep1:tmp1 = new tmp1()
Shape() {
Rect().width("100%").height("100%").fill("#0097D4")
Circle({ width: 150, height: 150 }).fill("#E87361")
}
.viewPort({ x: 0, y: 0, width: 300, height: 300 })
.viewPort(viep)
.width(300)
.height(300)
.backgroundColor("#F5DC62")
......@@ -110,7 +138,7 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei
Rect().width("100%").height("100%").fill("#0097D4")
Circle({ width: 150, height: 150 }).fill("#E87361")
}
.viewPort({ x: -150, y: -150, width: 300, height: 300 })
.viewPort(viep1)
.width(300)
.height(300)
.backgroundColor("#F5DC62")
......
......@@ -6,7 +6,7 @@
```ts
GestureGroup(mode:GestureMode, ...gesture:GestureType[])
GestureGroup(mode:GestureMode, gesture:GestureType[])
```
......@@ -53,9 +53,11 @@ struct Index {
// 该组合手势第一个触发的手势为长按手势,且长按手势可多次响应
LongPressGesture({ repeat: true })
// 当长按手势识别成功,增加Text组件上显示的count次数
.onAction((event: GestureEvent) => {
if (event.repeat) {
this.count++;
.onAction((event: GestureEvent|undefined) => {
if(event){
if (event.repeat) {
this.count++;
}
}
console.info('LongPress onAction');
})
......@@ -69,9 +71,11 @@ struct Index {
console.info('pan start');
})
// 当该手势被触发时,根据回调获得拖动的距离,修改该组件的位移距离从而实现组件的移动
.onActionUpdate((event: GestureEvent) => {
this.offsetX = this.positionX + event.offsetX;
this.offsetY = this.positionY + event.offsetY;
.onActionUpdate((event: GestureEvent|undefined) => {
if(event){
this.offsetX = this.positionX + event.offsetX;
this.offsetY = this.positionY + event.offsetY;
}
console.info('pan update');
})
.onActionEnd(() => {
......
......@@ -30,8 +30,10 @@ TapGesture(value?:{count?:number; fingers?:number})
.gesture(
// 绑定count为2的TapGesture
TapGesture({ count: 2 })
.onAction((event: GestureEvent) => {
.onAction((event: GestureEvent|undefined) => {
if(event){
this.value = JSON.stringify(event.fingerList[0]);
}
}))
Text(this.value)
}
......@@ -82,9 +84,11 @@ struct Index {
.gesture(
// 绑定可以重复触发的LongPressGesture
LongPressGesture({ repeat: true })
.onAction((event: GestureEvent) => {
if (event.repeat) {
this.count++;
.onAction((event: GestureEvent|undefined) => {
if(event){
if (event.repeat) {
this.count++;
}
}
})
.onActionEnd(() => {
......@@ -109,7 +113,13 @@ struct Index {
```ts
PanGestureOptions(value?:{ fingers?:number; direction?:PanDirection; distance?:number})
class pgotmp{
fingers?:number = 0
direction?:PanDirection|null = null
distance?:number = 0
}
let pgo:pgotmp = new pgotmp()
new PanGestureOptions(value?:pgo)
```
......@@ -150,13 +160,15 @@ struct Index {
.gesture(
// 绑定拖动手势
PanGesture()
.onActionStart((event: GestureEvent) => {
.onActionStart((event: GestureEvent|undefined) => {
console.info('Pan start');
})
// 当触发拖动手势时,根据回调函数修改组件的布局位置信息
.onActionUpdate((event: GestureEvent) => {
this.offsetX = this.positionX + event.offsetX;
this.offsetY = this.positionY + event.offsetY;
.onActionUpdate((event: GestureEvent|undefined) => {
if(event){
this.offsetX = this.positionX + event.offsetX;
this.offsetY = this.positionY + event.offsetY;
}
})
.onActionEnd(() => {
this.positionX = this.offsetX;
......@@ -226,14 +238,16 @@ struct Index {
.gesture(
// 在组件上绑定三指触发的捏合手势
PinchGesture({ fingers: 3 })
.onActionStart((event: GestureEvent) => {
.onActionStart((event: GestureEvent|undefined) => {
console.info('Pinch start');
})
// 当捏合手势触发时,可以通过回调函数获取缩放比例,从而修改组件的缩放比例
.onActionUpdate((event: GestureEvent) => {
this.scaleValue = this.pinchValue * event.scale;
this.pinchX = event.pinchCenterX;
this.pinchY = event.pinchCenterY;
.onActionUpdate((event: GestureEvent|undefined) => {
if(event){
this.scaleValue = this.pinchValue * event.scale;
this.pinchX = event.pinchCenterX;
this.pinchY = event.pinchCenterY;
}
})
.onActionEnd(() => {
this.pinchValue = this.scaleValue;
......@@ -284,12 +298,14 @@ struct Index {
.rotate({ angle: this.angle })
.gesture(
RotationGesture()
.onActionStart((event: GestureEvent) => {
.onActionStart((event: GestureEvent|undefined) => {
console.info('RotationGesture is onActionStart');
})
// 当旋转手势生效时,通过旋转手势的回调函数获取旋转角度,从而修改组件的旋转角度
.onActionUpdate((event: GestureEvent) => {
this.angle = this.rotateValue + event.angle;
.onActionUpdate((event: GestureEvent|undefined) => {
if(event){
this.angle = this.rotateValue + event.angle;
}
console.info('RotationGesture is onActionEnd');
})
// 当旋转结束抬手时,固定组件在旋转结束时的角度
......@@ -358,9 +374,11 @@ struct Index {
// 绑定滑动手势且限制仅在竖直方向滑动时触发
SwipeGesture({ direction: SwipeDirection.Vertical })
// 当滑动手势触发时,获取滑动的速度和角度,实现对组件的布局参数的修改
.onAction((event: GestureEvent) => {
this.speed = event.speed;
this.rotateAngle = event.angle;
.onAction((event: GestureEvent|undefined) => {
if(event){
this.speed = event.speed;
this.rotateAngle = event.angle;
}
})
)
}
......
......@@ -86,18 +86,20 @@ Image支持加载存档图、多媒体像素图两种类型。
getAllImg() {
let result = new Array<string>();
try {
let PhotoSelectOptions = new picker.PhotoSelectOptions();
let PhotoSelectOptions:picker.PhotoSelectOptions = new picker.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
PhotoSelectOptions.maxSelectNumber = 5;
let photoPicker = new picker.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => {
let photoPicker:picker.PhotoViewPicker = new picker.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult:picker.PhotoSelectResult) => {
this.imgDatas = PhotoSelectResult.photoUris;
console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
}).catch((err) => {
}).catch((err:Error) => {
console.error(`PhotoViewPicker.select failed with. Code: ${err.code}, message: ${err.message}`);
});
} catch (err) {
console.error(`PhotoViewPicker failed with. Code: ${err.code}, message: ${err.message}`); }
let message:BusinessError = (err as BusinessError).message;
let code:BusinessError = (err as BusinessError).code;
console.error(`PhotoViewPicker failed with. Code: ${code}, message: ${message}`); }
}
// aboutToAppear中调用上述函数,获取图库的所有图片url,存在imgDatas中
......@@ -108,12 +110,12 @@ Image支持加载存档图、多媒体像素图两种类型。
build() {
Column() {
Grid() {
ForEach(this.imgDatas, item => {
ForEach(this.imgDatas, (item:string) => {
GridItem() {
Image(item)
.width(200)
}
}, item => JSON.stringify(item))
}, ((item:string):string => JSON.stringify(item)))
}
}.width('100%').height('100%')
}
......@@ -156,7 +158,7 @@ PixelMap是图片解码后的像素图,具体用法请参考[图片开发指
2. 填写网络图片地址。
```ts
http.createHttp().request("https://www.example.com/xxx.png",
(error, data) => {
(error:Error) => {
if (error){
console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`);
} else {
......@@ -166,27 +168,47 @@ PixelMap是图片解码后的像素图,具体用法请参考[图片开发指
```
3. 将网络地址成功返回的数据,编码转码成pixelMap的图片格式。
```ts
let code = data.responseCode;
let code:object = data.responseCode;
if (ResponseCode.ResponseCode.OK === code) {
let res: any = data.result
let imageSource = image.createImageSource(res);
let options = {
alphaType: 0, // 透明度
editable: false, // 是否可编辑
pixelFormat: 3, // 像素格式
scaleMode: 1, // 缩略值
size: { height: 100, width: 100 }
let imageSource:image = image.createImageSource(data.result);
class tmp{
height:number = 100
width:number = 100
}
let si:tmp = new tmp()
let options:Record<string,number|boolean|tmp> = {
'alphaType': 0, // 透明度
'editable': false, // 是否可编辑
'pixelFormat': 3, // 像素格式
'scaleMode': 1, // 缩略值
'size': { height: 100, width: 100 }
} // 创建图片大小
imageSource.createPixelMap(options).then((pixelMap) => {
this.image = pixelMap
})
class imagetmp{
image:image
set(val:PixelMap){
this.image = val
}
}
imageSource.createPixelMap(options).then((pixelMap:PixelMap) => {
let im = new imagetmp()
im.set(pixelMap)
})
}
```
4. 显示图片。
```ts
class htp{
httpRequest:Function|undefined = undefined
set(){
if(this.httpRequest){
this.httpRequest()
}
}
}
Button("获取网络图片")
.onClick(() => {
this.httpRequest()
let sethtp = new htp()
sethtp.set()
})
Image(this.image).height(100).width(100)
```
......@@ -498,6 +520,14 @@ Image($r('app.media.icon'))
```ts
class tmp{
width: number = 0
height: number = 0
componentWidth: number = 0
componentHeight: number = 0
}
let msg:tmp = new tmp()
@Entry
@Component
struct MyComponent {
......@@ -513,16 +543,13 @@ struct MyComponent {
.width(200)
.height(150)
.margin(15)
.onComplete((msg: {
width: number,
height: number,
componentWidth: number,
componentHeight: number
}) => {
this.widthValue = msg.width
this.heightValue = msg.height
this.componentWidth = msg.componentWidth
this.componentHeight = msg.componentHeight
.onComplete(msg => {
if(msg){
this.widthValue = msg.width
this.heightValue = msg.height
this.componentWidth = msg.componentWidth
this.componentHeight = msg.componentHeight
}
})
// 图片获取失败,打印结果
.onError(() => {
......
......@@ -185,15 +185,14 @@ struct OfficeService {
build() {
Column() {
Grid() {
ForEach(this.services, service => {
ForEach(this.services, (service:string) => {
GridItem() {
Text(service)
...
}
}, service => service)
}, ((service:string):string => service))
}
.rowsTemplate('1fr 1fr')
.columnsTemplate('1fr 1fr')
.rowsTemplate(('1fr 1fr') as string)
.columnsTemplate(('1fr 1fr') as string)
...
}
...
......@@ -238,24 +237,20 @@ Grid() {
```ts
@Component
struct Shopping {
@State services: Array<string> = ['直播', '进口', ...]
...
@State services: Array<string> = ['直播', '进口']
build() {
Column({ space: 5 }) {
Grid() {
ForEach(this.services, (service: string, index) => {
GridItem() {
...
}
.width('25%')
}, service => service)
}, ((service:string):string => service))
}
.rowsTemplate('1fr 1fr') // 只设置rowsTemplate属性,当内容超出Grid区域时,可水平滚动。
.rowsGap(15)
...
}
...
}
}
```
......@@ -273,13 +268,19 @@ Grid组件初始化时,可以绑定一个[Scroller](../reference/arkui-ts/ts-c
```ts
private scroller: Scroller = new Scroller()
export let scroller: Scroller = new Scroller()
```
在日历页面中,用户在点击“下一页”按钮时,应用响应点击事件,通过指定scrollPage方法的参数next为true,滚动到下一页。
```ts
class Tmp{
scroller: Scroller = new Scroller()
set(boo:boolean){
this.scroller.scrollPage({next:boo})
}
}
Column({ space: 5 }) {
Grid(this.scroller) {
...
......@@ -290,16 +291,14 @@ Column({ space: 5 }) {
Row({space: 20}) {
Button('上一页')
.onClick(() => {
this.scroller.scrollPage({
next: false
})
let ClickN = new Tmp()
ClickN.set(false)
})
Button('下一页')
.onClick(() => {
this.scroller.scrollPage({
next: true
})
let ClickN = new Tmp()
ClickN.set(true)
})
}
}
......@@ -319,9 +318,8 @@ Column({ space: 5 }) {
```ts
Grid() {
LazyForEach(this.dataSource, item => {
LazyForEach(this.dataSource, () => {
GridItem() {
...
}
})
}
......
......@@ -99,20 +99,30 @@ List组件的lanes属性通常用于在不同尺寸的设备自适应构建不
```ts
class Tmp{
minLength:number = 200
maxLength:number = 300
}
let Mn:Tmp = new Tmp()
List() {
...
}
.lanes(2)
.lanes(Mn)
```
当其取值为LengthConstrain类型时,表示会根据LengthConstrain与List组件的尺寸自适应决定行或列数。
```ts
class Tmp{
minLength:number = 200
maxLength:number = 300
}
let mn:Tmp = new Tmp()
List() {
...
}
.lanes({ minLength: 200, maxLength: 300 })
.lanes(mn)
```
例如,假设在垂直列表中设置了lanes的值为{ minLength: 200, maxLength: 300 }。此时,
......@@ -229,10 +239,9 @@ class Contact {
@Entry
@Component
struct SimpleContacts {
private contacts = [
private contacts:Array<object> = [
new Contact('小明', $r("app.media.iconA")),
new Contact('小红', $r("app.media.iconB")),
...
]
build() {
......@@ -249,7 +258,7 @@ struct SimpleContacts {
.width('100%')
.justifyContent(FlexAlign.Start)
}
}, item => item.key)
}, ((item:Contact):string => item.key))
}
.width('100%')
}
......@@ -288,15 +297,16 @@ startMargin和endMargin属性分别用于设置分隔线距离列表侧边起始
```ts
let opt = {
'strokeWidth': 1,
'startMargin': 60,
'endMargin': 10,
'color': '#ffe9f0f0'
} as Record<string,number|string>
List() {
...
}
.divider({
strokeWidth: 1,
startMargin: 60,
endMargin: 10,
color: '#ffe9f0f0'
})
.divider(opt)
```
此示例表示从距离列表侧边起始端60vp开始到距离结束端10vp的位置,画一条粗细为1vp的分割线,可以实现图9设置列表分隔线的样式。
......@@ -378,7 +388,11 @@ struct ContactsList {
```ts
contactsGroups: object[] = [
class cgtmp{
title:string = ''
contacts:Array<object>|null = null
}
export let contactsGroups: object[] = [
{
title: 'A',
contacts: [
......@@ -386,15 +400,14 @@ contactsGroups: object[] = [
new Contact('安安', $r('app.media.iconB')),
new Contact('Angela', $r('app.media.iconC')),
],
},
} as cgtmp,
{
title: 'B',
contacts: [
new Contact('白叶', $r('app.media.iconD')),
new Contact('伯明', $r('app.media.iconE')),
],
},
...
} as cgtmp,
]
```
......@@ -402,18 +415,30 @@ contactsGroups: object[] = [
```ts
class cgtmpf{
title:string = ''
contacts:Array<object>|null = null
key:string = ''
}
class heF{
itemHead:Function = (text: string) => {}
foo(val:string){
this.itemHead(val)
}
}
let fff:heF = this.heF()
List() {
// 循环渲染ListItemGroup,contactsGroups为多个分组联系人contacts和标题title的数据集合
ForEach(this.contactsGroups, item => {
ListItemGroup({ header: this.itemHead(item.title) }) {
ForEach(contactsGroups, (item: cgtmpf) => {
ListItemGroup({ header: fff(item.title) }) {
// 循环渲染ListItem
ForEach(item.contacts, (contact) => {
ListItem() {
...
}
}, item => item.key)
if (item.contacts) {
ForEach(item.contacts, () => {
ListItem() {
}
}, ((item: cgtmpf): string => item.key))
}
}
...
})
}
```
......@@ -452,16 +477,16 @@ struct ContactsList {
build() {
List() {
// 循环渲染ListItemGroup,contactsGroups为多个分组联系人contacts和标题title的数据集合
ForEach(this.contactsGroups, item => {
ForEach(contactsGroups, (item:cgtmpf) => {
ListItemGroup({ header: this.itemHead(item.title) }) {
// 循环渲染ListItem
ForEach(item.contacts, (contact) => {
ListItem() {
...
}
}, item => item.key)
if(item.contacts){
ForEach(item.contacts, () => {
ListItem() {
}
}, ((item:cgtmpf):string => item.key))
}
}
...
})
}
.sticky(StickyStyle.Header) // 设置吸顶,实现粘性标题效果
......@@ -484,14 +509,15 @@ List组件初始化时,可以通过scroller参数绑定一个[Scroller](../ref
```ts
private listScroller: Scroller = new Scroller();
export let listScroller: Scroller = new Scroller();
```
然后,通过将listScroller用于初始化List组件的scroller参数,完成listScroller与列表的绑定。在需要跳转的位置指定scrollToIndex的参数为0,表示返回列表顶部。
```ts
Stack({ alignContent: Alignment.BottomEnd }) {
let sttmo:Record<string,Alignment> = { 'alignContent': Alignment.BottomEnd }
Stack(sttmo) {
// 将listScroller用于初始化List组件的scroller参数,完成listScroller与列表的绑定。
List({ space: 20, scroller: this.listScroller }) {
...
......@@ -503,7 +529,7 @@ Stack({ alignContent: Alignment.BottomEnd }) {
}
.onClick(() => {
// 点击按钮时,指定跳转位置,返回列表顶部
this.listScroller.scrollToIndex(0)
listScroller.scrollToIndex(0)
})
...
}
......@@ -544,7 +570,6 @@ struct ContactsList {
}
.onScrollIndex((firstIndex: number) => {
// 根据列表滚动到的索引值,重新计算对应联系人索引栏的位置this.selectedIndex
...
})
...
......@@ -576,12 +601,22 @@ ListItem的swipeAction属性可用于实现列表项的左右滑动功能。swip
```ts
class swtmp{
temp:Record<string,object> = {}
itemEnd:Function|undefined = undefined
get(index:number){
if(this.itemEnd){
this.temp = {'end':this.itemEnd(this, index)}
}
return this.temp
}
}
let swipertmp:swtmp = new swtmp()
@Entry
@Component
struct MessageList {
@State messages: object[] = [
// 初始化消息列表数据
...
];
@Builder itemEnd(index: number) {
......@@ -600,12 +635,13 @@ struct MessageList {
build() {
...
List() {
ForEach(this.messages, (item, index) => {
ListItem() {
...
ForEach(this.messages, (item:MessageList, index:number|undefined) => {
if(index){
ListItem() {
}
.swipeAction(swipertmp.get(index)) // 设置侧滑属性.
}
.swipeAction({ end: this.itemEnd.bind(this, index) }) // 设置侧滑属性
}, item => item.id.toString())
}, ((item:MessageList):string => item.id.toString()))
}
...
}
......@@ -691,18 +727,27 @@ Badge({
```ts
@State toDoData: ToDo[] = [];
private availableThings: string[] = ['读书', '运动', '旅游', '听音乐', '看电影', '唱歌'];
export let availableThings: string[] = ['读书', '运动', '旅游', '听音乐', '看电影', '唱歌'];
```
最后,构建列表布局和列表项:
```ts
export class ToDo {
key: string = util.generateRandomUUID(true);
name: string;
toDoData:ToDo[] = [];
constructor(name: string) {
this.name = name;
}
}
let todo:ToDo = new ToDo()
List({ space: 10 }) {
ForEach(this.toDoData, (toDoItem) => {
ForEach(todo.toDoData, (toDoItem:ToDo) => {
ListItem() {
...
}
}, toDoItem => toDoItem.key)
}, ((toDoItem:ToDo):string => toDoItem.key))
}
```
......@@ -715,9 +760,9 @@ Badge({
Text('+')
.onClick(() => {
TextPickerDialog.show({
range: this.availableThings,
range: availableThings,
onAccept: (value: TextPickerResult) => {
this.toDoData.push(new ToDo(this.availableThings[value.index])); // 新增列表项数据toDoData
todo.toDoData.push(new ToDo(availableThings[value.index])); // 新增列表项数据toDoData
},
})
})
......@@ -737,64 +782,105 @@ Badge({
1. 列表的删除功能一般进入编辑模式后才可使用,所以需要提供编辑模式的入口。
以待办列表为例,通过监听列表项的长按事件,当用户长按列表项时,进入编辑模式。
```ts
```ts
class todoTmp{
isEditMode:boolean = false
selectedItems:Array<object> = []
toDoItem:ToDo[] = [];
toDoData:ToDo[] = [];
}
let todolist:todoTmp = new todoTmp()
// ToDoListItem.ets
Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
...
}
.gesture(
GestureGroup(GestureMode.Exclusive,
LongPressGesture()
.onAction(() => {
if (!this.isEditMode) {
this.isEditMode = true; //进入编辑模式
this.selectedItems.push(this.toDoItem); // 记录长按时选中的列表项
}
})
)
)
Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
...
}
.gesture(
GestureGroup(GestureMode.Exclusive,
LongPressGesture()
.onAction(() => {
if (!todolist.isEditMode) {
todolist.isEditMode = true; //进入编辑模式
todolist.selectedItems.push(todolist.toDoItem); // 记录长按时选中的列表项
}
})
)
)
```
2. 需要响应用户的选择交互,记录要删除的列表项数据。
在待办列表中,通过勾选框的勾选或取消勾选,响应用户勾选列表项变化,记录所有选择的列表项。
```ts
```ts
import util from '@ohos.util';
export class ToDo {
key: string = util.generateRandomUUID(true);
name: string;
toDoData:ToDo[] = [];
constructor(name: string) {
this.name = name;
}
}
class todoTmp{
isEditMode:boolean = false
selectedItems:Array<object> = []
toDoItem:ToDo[] = [];
toDoData:ToDo[] = [];
}
let todolist:todoTmp = new todoTmp()
// ToDoListItem.ets
if (this.isEditMode) {
Checkbox()
.onChange((isSelected) => {
if (isSelected) {
this.selectedItems.push(this.toDoItem) // 勾选时,记录选中的列表项
} else {
let index = this.selectedItems.indexOf(this.toDoItem)
if (index !== -1) {
this.selectedItems.splice(index, 1) // 取消勾选时,则将此项从selectedItems中删除
}
}
})
...
}
if (todolist.isEditMode) {
Checkbox()
.onChange((isSelected) => {
if (isSelected) {
todolist.selectedItems.push(todolist.toDoItem) // 勾选时,记录选中的列表项
} else {
let index = todolist.selectedItems.indexOf(todolist.toDoItem)
if (index !== -1) {
todolist.selectedItems.splice(index, 1) // 取消勾选时,则将此项从selectedItems中删除
}
}
})
...
}
```
3. 需要响应用户点击删除按钮事件,删除列表中对应的选项。
```ts
```ts
import util from '@ohos.util';
export class ToDo {
key: string = util.generateRandomUUID(true);
name: string;
toDoData:ToDo[] = [];
constructor(name: string) {
this.name = name;
}
}
class todoTmp{
isEditMode:boolean = false
selectedItems:Array<object> = []
toDoItem:ToDo[] = [];
toDoData:ToDo[] = [];
}
let todolist:todoTmp = new todoTmp()
// ToDoList.ets
Button('删除')
.onClick(() => {
// 删除选中的列表项对应的toDoData数据
let leftData = this.toDoData.filter((item) => {
return this.selectedItems.find((selectedItem) => selectedItem !== item);
})
Button('删除')
.onClick(() => {
// 删除选中的列表项对应的toDoData数据
let leftData = todolist.toDoData.filter((item) => {
return todolist.selectedItems.find((selectedItem) => selectedItem !== item);
})
this.toDoData = leftData;
this.isEditMode = false;
})
...
```
todolist.toDoData = leftData;
todolist.isEditMode = false;
})
...
```
## 长列表的处理
......@@ -807,12 +893,17 @@ Badge({
```ts
class dataTmp{
dataSource:IDataSource|undefined = undefined
}
let ds:dataTmp = new dataTmp()
List() {
LazyForEach(this.dataSource, item => {
ListItem() {
...
}
})
if(ds.dataSource){
LazyForEach(ds.dataSource, () => {
ListItem() {
}
})
}
}.cachedCount(3)
```
......
......@@ -19,7 +19,7 @@ Swiper作为一个容器组件,在自身尺寸属性未被设置时,会自
```ts
...
private swiperController: SwiperController = new SwiperController()
export let swiperController: SwiperController = new SwiperController()
...
Swiper(this.swiperController) {
Text("0")
......@@ -156,6 +156,7 @@ Swiper(this.swiperController) {
自定义导航点样式(示例:导航点直径设为30VP,左边距为0,导航点颜色设为红色):
```ts
let swco:Record<string,number|Color> = {'size':30,'left':0,'color':Color.Red}
Swiper(this.swiperController) {
Text("0")
.width('90%')
......@@ -178,11 +179,7 @@ Swiper(this.swiperController) {
.textAlign(TextAlign.Center)
.fontSize(30)
}
.indicatorStyle({
size: 30,
left: 0,
color: Color.Red
})
.indicatorStyle(swco)
```
![ind](figures/ind.PNG)
......
......@@ -159,13 +159,14 @@
```ts
let PTopBottom:Record<string,number> = { 'top': 10, 'bottom': 10 }
Flex({ justifyContent: FlexAlign.Start }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding({ top: 10, bottom: 10 })
.padding(PTopBottom)
.backgroundColor(0xAFEEEE)
```
......@@ -175,13 +176,14 @@
```ts
let PTopBottom:Record<string,number> = { 'top': 10, 'bottom': 10 }
Flex({ justifyContent: FlexAlign.Center }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding({ top: 10, bottom: 10 })
.padding(PTopBottom)
.backgroundColor(0xAFEEEE)
```
......@@ -191,13 +193,14 @@
```ts
let PTopBottom:Record<string,number> = { 'top': 10, 'bottom': 10 }
Flex({ justifyContent: FlexAlign.End }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding({ top: 10, bottom: 10 })
.padding(PTopBottom)
.backgroundColor(0xAFEEEE)
```
......@@ -207,13 +210,14 @@
```ts
let PTopBottom1:Record<string,number> = { 'top': 10, 'bottom': 10 }
Flex({ justifyContent: FlexAlign.SpaceBetween }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding({ top: 10, bottom: 10 })
.padding(PTopBottom1)
.backgroundColor(0xAFEEEE)
```
......@@ -223,13 +227,14 @@
```ts
let PTopBottom:Record<string,number> = { 'top': 10, 'bottom': 10 }
Flex({ justifyContent: FlexAlign.SpaceAround }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding({ top: 10, bottom: 10 })
.padding(PTopBottom)
.backgroundColor(0xAFEEEE)
```
......@@ -239,13 +244,14 @@
```ts
let PTopBottom:Record<string,number> = { 'top': 10, 'bottom': 10 }
Flex({ justifyContent: FlexAlign.SpaceEvenly }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
}
.width('90%')
.padding({ top: 10, bottom: 10 })
.padding(PTopBottom)
.backgroundColor(0xAFEEEE)
```
......@@ -266,12 +272,13 @@
```ts
let SWh:Record<string,number|string> = { 'width': '90%', 'height': 80 }
Flex({ alignItems: ItemAlign.Auto }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.size({ width: '90%', height: 80 })
.size(SWh)
.padding(10)
.backgroundColor(0xAFEEEE)
```
......@@ -282,12 +289,13 @@
```ts
let SWh:Record<string,number|string> = { 'width': '90%', 'height': 80 }
Flex({ alignItems: ItemAlign.Start }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.size({ width: '90%', height: 80 })
.size(SWh)
.padding(10)
.backgroundColor(0xAFEEEE)
```
......@@ -298,12 +306,13 @@
```ts
let SWh:Record<string,number|string> = { 'width': '90%', 'height': 80 }
Flex({ alignItems: ItemAlign.Center }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.size({ width: '90%', height: 80 })
.size(SWh)
.padding(10)
.backgroundColor(0xAFEEEE)
```
......@@ -314,12 +323,13 @@
```ts
let SWh:Record<string,number|string> = { 'width': '90%', 'height': 80 }
Flex({ alignItems: ItemAlign.End }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.size({ width: '90%', height: 80 })
.size(SWh)
.padding(10)
.backgroundColor(0xAFEEEE)
```
......@@ -330,12 +340,13 @@
```ts
let SWh:Record<string,number|string> = { 'width': '90%', 'height': 80 }
Flex({ alignItems: ItemAlign.Stretch }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.size({ width: '90%', height: 80 })
.size(SWh)
.padding(10)
.backgroundColor(0xAFEEEE)
```
......@@ -346,12 +357,13 @@
```ts
let SWh:Record<string,number|string> = { 'width': '90%', 'height': 80 }
Flex({ alignItems: ItemAlign.Baseline }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
}
.size({ width: '90%', height: 80 })
.size(SWh)
.padding(10)
.backgroundColor(0xAFEEEE)
```
......
......@@ -73,7 +73,7 @@ GridRow({
reference: BreakpointsReference.WindowSize
}
}) {
ForEach(this.bgColors, (color, index) => {
ForEach(this.bgColors, (color:Color, index?:number|undefined) => {
GridCol({
span: {
xs: 2,
......@@ -106,12 +106,14 @@ GridRow中通过columns设置栅格布局的总列数。
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown];
...
GridRow() {
ForEach(this.bgColors, (item, index) => {
GridCol() {
Row() {
Text(`${index + 1}`)
}.width('100%').height('50')
}.backgroundColor(item)
ForEach(this.bgColors, (item:Color, index?:number|undefined) => {
if(index){
GridCol() {
Row() {
Text(`${index + 1}`)
}.width('100%').height('50')
}.backgroundColor(item)
}
})
}
```
......@@ -122,45 +124,58 @@ GridRow中通过columns设置栅格布局的总列数。
```ts
class CurrTmp{
currentBp: string = 'unknown';
set(val:string){
this.currentBp = val
}
}
let BorderWH:Record<string,Color|number> = { 'color': Color.Blue, 'width': 2 }
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown];
@State currentBp: string = 'unknown';
...
Row() {
GridRow({ columns: 4 }) {
ForEach(this.bgColors, (item, index) => {
GridCol() {
Row() {
Text(`${index + 1}`)
}.width('100%').height('50')
}.backgroundColor(item)
ForEach(this.bgColors, (item:Color, index?:number|undefined) => {
if(index){
GridCol() {
Row() {
Text(`${index.toString() + 1}`)
}.width('100%').height('50')
}.backgroundColor(item)
}
})
}
.width('100%').height('100%')
.onBreakpointChange((breakpoint) => {
this.currentBp = breakpoint
.onBreakpointChange((breakpoint:string) => {
let CurrSet:CurrTmp = new CurrTmp()
CurrSet.set(breakpoint)
})
}
.height(160)
.border({ color: Color.Blue, width: 2 })
.border(BorderWH)
.width('90%')
Row() {
GridRow({ columns: 8 }) {
ForEach(this.bgColors, (item, index) => {
GridCol() {
Row() {
Text(`${index + 1}`)
}.width('100%').height('50')
}.backgroundColor(item)
ForEach(this.bgColors, (item:Color, index?:number|undefined) => {
if(index){
GridCol() {
Row() {
Text(`${index.toString() + 1}`)
}.width('100%').height('50')
}.backgroundColor(item)
}
})
}
.width('100%').height('100%')
.onBreakpointChange((breakpoint) => {
this.currentBp = breakpoint
.onBreakpointChange((breakpoint:string) => {
let CurrSet:CurrTmp = new CurrTmp()
CurrSet.set(breakpoint)
})
}
.height(160)
.border({ color: Color.Blue, width: 2 })
.border(BorderWH)
.width('90%')
```
......@@ -172,12 +187,14 @@ GridRow中通过columns设置栅格布局的总列数。
```ts
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown]
GridRow({ columns: { sm: 4, md: 8 }, breakpoints: { value: ['200vp', '300vp', '400vp', '500vp', '600vp'] } }) {
ForEach(this.bgColors, (item, index) => {
GridCol() {
Row() {
Text(`${index + 1}`)
}.width('100%').height('50')
}.backgroundColor(item)
ForEach(this.bgColors, (item:Color, index?:number|undefined) => {
if(index){
GridCol() {
Row() {
Text(`${index.toString() + 1}`)
}.width('100%').height('50')
}.backgroundColor(item)
}
})
}
```
......@@ -241,30 +258,33 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设
```ts
let Gspan:Record<string,number> = { 'xs': 1, 'sm': 2, 'md': 3, 'lg': 4 }
GridCol({ span: 2 }){}
GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }){}
GridCol(){}.span(2)
GridCol(){}.span({ xs: 1, sm: 2, md: 3, lg: 4 })
GridCol(){}.span(Gspan)
```
- 设置offset。
```ts
let Goffset:Record<string,number> = { 'xs': 1, 'sm': 2, 'md': 3, 'lg': 4 }
GridCol({ offset: 2 }){}
GridCol({ offset: { xs: 2, sm: 2, md: 2, lg: 2 } }){}
GridCol(){}.offset(2)
GridCol(){}.offset({ xs: 1, sm: 2, md: 3, lg: 4 })
GridCol(){}.offset(Goffset)
```
- 设置order。
```ts
let Gorder:Record<string,number> = { 'xs': 1, 'sm': 2, 'md': 3, 'lg': 4 }
GridCol({ order: 2 }){}
GridCol({ order: { xs: 1, sm: 2, md: 3, lg: 4 } }){}
GridCol(){}.order(2)
GridCol(){}.order({ xs: 1, sm: 2, md: 3, lg: 4 })
GridCol(){}.order(Gorder)
```
......@@ -279,7 +299,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown];
...
GridRow({ columns: 8 }) {
ForEach(this.bgColors, (color, index) => {
ForEach(this.bgColors, (color:Color, index?:number|undefined) => {
GridCol({ span: 2 }) {
Row() {
Text(`${index}`)
......@@ -299,7 +319,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown];
...
GridRow({ columns: 8 }) {
ForEach(this.bgColors, (color, index) => {
ForEach(this.bgColors, (color:Color, index?:number|undefined) => {
GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }) {
Row() {
Text(`${index}`)
......@@ -324,7 +344,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown];
...
GridRow() {
ForEach(this.bgColors, (color, index) => {
ForEach(this.bgColors, (color:Color, index?:number|undefined) => {
GridCol({ offset: 2 }) {
Row() {
Text('' + index)
......@@ -347,7 +367,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设
...
GridRow() {
ForEach(this.bgColors, (color, index) => {
ForEach(this.bgColors, (color:Color, index?:number|undefined) => {
GridCol({ offset: { xs: 1, sm: 2, md: 3, lg: 4 } }) {
Row() {
Text('' + index)
......
......@@ -567,8 +567,9 @@ struct BlankExample {
build() {
Scroll(this.scroller) {
Column() {
ForEach(this.arr, (item) => {
Text(item.toString())
ForEach(this.arr, (item?:number|undefined) => {
if(item){
Text(item.toString())
.width('90%')
.height(150)
.backgroundColor(0xFFFFFF)
......@@ -576,7 +577,8 @@ struct BlankExample {
.fontSize(16)
.textAlign(TextAlign.Center)
.margin({ top: 10 })
}, item => item)
}
}, ((item:string):string => item))
}.width('100%')
}
.backgroundColor(0xDCDCDC)
......@@ -604,8 +606,9 @@ struct BlankExample {
build() {
Scroll(this.scroller) {
Row() {
ForEach(this.arr, (item) => {
Text(item.toString())
ForEach(this.arr, (item?:number|undefined) => {
if(item){
Text(item.toString())
.height('90%')
.width(150)
.backgroundColor(0xFFFFFF)
......@@ -613,6 +616,7 @@ struct BlankExample {
.fontSize(16)
.textAlign(TextAlign.Center)
.margin({ left: 10 })
}
})
}.height('100%')
}
......
......@@ -25,15 +25,15 @@ import mediaquery from '@ohos.mediaquery';
```ts
let listener = mediaquery.matchMediaSync('(orientation: landscape)');
let listener:mediaquery = mediaquery.matchMediaSync('(orientation: landscape)');
```
给条件监听句柄listener绑定回调函数onPortrait,当listener检测设备状态变化时执行回调函数。在回调函数内,根据不同设备状态更改页面布局或者实现业务逻辑。
```ts
onPortrait(mediaQueryResult) {
if (mediaQueryResult.matches) {
onPortrait(mediaQueryResult:mediaquery) {
if (mediaQueryResult.matches as boolean) {
// do something here
} else {
// do something here
......@@ -143,19 +143,18 @@ import mediaquery from '@ohos.mediaquery';
import window from '@ohos.window';
import common from '@ohos.app.ability.common';
let portraitFunc = null;
export let portraitFunc:mediaquery.MediaQueryResult|void|null = null;
@Entry
@Component
struct MediaQueryExample {
@State color: string = '#DB7093';
@State text: string = 'Portrait';
// 当设备横屏时条件成立
listener = mediaquery.matchMediaSync('(orientation: landscape)');
listener:mediaquery = mediaquery.matchMediaSync('(orientation: landscape)');
// 当满足媒体查询条件时,触发回调
onPortrait(mediaQueryResult) {
if (mediaQueryResult.matches) { // 若设备为横屏状态,更改相应的页面布局
onPortrait(mediaQueryResult:mediaquery) {
if (mediaQueryResult.matches as boolean) { // 若设备为横屏状态,更改相应的页面布局
this.color = '#FFD700';
this.text = 'Landscape';
} else {
......@@ -166,7 +165,7 @@ struct MediaQueryExample {
aboutToAppear() {
// 绑定当前应用实例
portraitFunc = this.onPortrait.bind(this);
portraitFunc = this.onPortrait(this);
// 绑定回调函数
this.listener.on('change', portraitFunc);
}
......@@ -174,7 +173,7 @@ struct MediaQueryExample {
// 改变设备横竖屏状态函数
private changeOrientation(isLandscape: boolean) {
// 获取UIAbility实例的上下文信息
let context = getContext(this) as common.UIAbilityContext;
let context:common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
// 调用该接口手动改变设备横竖屏状态
window.getLastWindow(context).then((lastWindow) => {
lastWindow.setPreferredOrientation(isLandscape ? window.Orientation.LANDSCAPE : window.Orientation.PORTRAIT)
......@@ -205,17 +204,17 @@ FA模型下的示例:
import mediaquery from '@ohos.mediaquery';
import featureAbility from '@ohos.ability.featureAbility';
let portraitFunc = null;
let portraitFunc:mediaquery.MediaQueryResult|void|null = null;
@Entry
@Component
struct MediaQueryExample {
@State color: string = '#DB7093';
@State text: string = 'Portrait';
listener = mediaquery.matchMediaSync('(orientation: landscape)'); // 当设备横屏时条件成立
listener:mediaquery = mediaquery.matchMediaSync('(orientation: landscape)'); // 当设备横屏时条件成立
onPortrait(mediaQueryResult) { // 当满足媒体查询条件时,触发回调
if (mediaQueryResult.matches) { // 若设备为横屏状态,更改相应的页面布局
onPortrait(mediaQueryResult:mediaquery) { // 当满足媒体查询条件时,触发回调
if (mediaQueryResult.matches as boolean) { // 若设备为横屏状态,更改相应的页面布局
this.color = '#FFD700';
this.text = 'Landscape';
} else {
......@@ -225,7 +224,7 @@ struct MediaQueryExample {
}
aboutToAppear() {
portraitFunc = this.onPortrait.bind(this); // 绑定当前应用实例
portraitFunc = this.onPortrait(this); // 绑定当前应用实例
this.listener.on('change', portraitFunc); //绑定回调函数
}
......@@ -234,12 +233,12 @@ struct MediaQueryExample {
Text(this.text).fontSize(50).fontColor(this.color)
Text('Landscape').fontSize(50).fontColor(this.color).backgroundColor(Color.Orange)
.onClick(() => {
let context = featureAbility.getContext();
let context:featureAbility = featureAbility.getContext();
context.setDisplayOrientation(0); //调用该接口手动改变设备横竖屏状态
})
Text('Portrait').fontSize(50).fontColor(this.color).backgroundColor(Color.Orange)
.onClick(() => {
let context = featureAbility.getContext();
let context:featureAbility = featureAbility.getContext();
context.setDisplayOrientation(1); //调用该接口手动改变设备横竖屏状态
})
}
......
......@@ -35,24 +35,25 @@
- RelativeContainer父组件为锚点,__container__代表父容器的id。
```ts
let AlignRus:Record<string,Record<string,string|VerticalAlign|HorizontalAlign>> = {
'top': { 'anchor': '__container__', 'align': VerticalAlign.Top },
'left': { 'anchor': '__container__', 'align': HorizontalAlign.Start }
}
let AlignRue:Record<string,Record<string,string|VerticalAlign|HorizontalAlign>> = {
'top': { 'anchor': '__container__', 'align': VerticalAlign.Top },
'left': { 'anchor': '__container__', 'align': HorizontalAlign.End }
}
RelativeContainer() {
Row()
// 添加其他属性
.alignRules({
top: { anchor: '__container__', align: VerticalAlign.Top },
left: { anchor: '__container__', align: HorizontalAlign.Start }
})
.alignRules(AlignRus)
.id("row1")
Row()
...
.alignRules({
top: { anchor: '__container__', align: VerticalAlign.Top },
right: { anchor: '__container__', align: HorizontalAlign.End }
})
.alignRules(AlignRue)
.id("row2")
}
...
```
![zh-cn_image_0000001562820901](figures/zh-cn_image_0000001562820901.png)
......@@ -60,14 +61,15 @@
- 以子元素为锚点。
```ts
RelativeContainer() {
...
top: { anchor: 'row1', align: VerticalAlign.Bottom },
...
let RelConB:Record<string,Record<string,string|VerticalAlign|HorizontalAlign>> = {
'top': { 'anchor': 'row1', 'align': VerticalAlign.Bottom }
}
let Mleft:Record<string,number> = { 'left': 20 }
let BWC:Record<string,number|string> = { 'width': 2, 'color': '#6699FF' }
RelativeContainer() {RelConB}
.width(300).height(300)
.margin({ left: 20 })
.border({ width: 2, color: '#6699FF' })
.margin(Mleft)
.border(BWC)
```
![zh-cn_image_0000001562940613](figures/zh-cn_image_0000001562940613.png)
......
......@@ -22,12 +22,13 @@ Stack组件为容器组件,容器内可包含各种子组件。其中的子组
```ts
let MTop:Record<string,number> = { 'top': 50 }
Column(){
Stack({ }) {
Column(){}.width('90%').height('100%').backgroundColor('#ff58b87c')
Text('text').width('60%').height('60%').backgroundColor('#ffc3f6aa')
Button('button').width('30%').height('30%').backgroundColor('#ff8ff3eb').fontColor('#000')
}.width('100%').height(150).margin({ top: 50 })
}.width('100%').height(150).margin(MTop)
}
```
......@@ -51,6 +52,7 @@ Stack容器中兄弟组件显示层级关系可以通过[Z序控制](../referenc
在层叠布局中,如果后面子元素尺寸大于前面子元素尺寸,则前面子元素完全隐藏。
```ts
let MTopM1:Record<string,number> = { 'top': 100 }
Stack({ alignContent: Alignment.BottomStart }) {
Column() {
Text('Stack子元素1').textAlign(TextAlign.End).fontSize(20)
......@@ -63,7 +65,7 @@ Stack({ alignContent: Alignment.BottomStart }) {
Column() {
Text('Stack子元素3').fontSize(20)
}.width(200).height(200).backgroundColor(Color.Grey)
}.margin({ top: 100 }).width(350).height(350).backgroundColor(0xe0e0e0)
}.margin(MTopM1).width(350).height(350).backgroundColor(0xe0e0e0)
```
![zh-cn_image_0000001511900544](figures/zh-cn_image_0000001511900544.png)
......@@ -72,6 +74,7 @@ Stack({ alignContent: Alignment.BottomStart }) {
```ts
let MTopM:Record<string,number> = { 'top': 100 }
Stack({ alignContent: Alignment.BottomStart }) {
Column() {
Text('Stack子元素1').fontSize(20)
......@@ -84,7 +87,7 @@ Stack({ alignContent: Alignment.BottomStart }) {
Column() {
Text('Stack子元素3').fontSize(20)
}.width(200).height(200).backgroundColor(Color.Grey)
}.margin({ top: 100 }).width(350).height(350).backgroundColor(0xe0e0e0)
}.margin(MTopM).width(350).height(350).backgroundColor(0xe0e0e0)
```
![zh-cn_image_0000001563060797](figures/zh-cn_image_0000001563060797.png)
......@@ -104,7 +107,7 @@ struct StackSample {
build() {
Stack({ alignContent: Alignment.Bottom }) {
Flex({ wrap: FlexWrap.Wrap }) {
ForEach(this.arr, (item) => {
ForEach(this.arr, (item:string) => {
Text(item)
.width(100)
.height(100)
......@@ -113,7 +116,7 @@ struct StackSample {
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(0xFFFFFF)
}, item => item)
}, ((item:string):string => item))
}.width('100%').height('100%')
Flex({ justifyContent: FlexAlign.SpaceAround, alignItems: ItemAlign.Center }) {
......
......@@ -38,6 +38,12 @@
3. 通过模态接口调起模态展示界面,通过转场动画或者共享元素动画去实现对应的动画效果。
```ts
class PresentTmp{
isPresent: boolean = false;
set(){
this.isPresent = !this.isPresent;
}
}
// 模态转场控制变量
@State isPresent: boolean = false;
......@@ -46,7 +52,8 @@
.bindContentCover($$this.isPresent, this.MyBuilder, ModalTransition.None)
.onClick(() => {
// 改变状态变量,让模态界面显示
this.isPresent = !this.isPresent;
let setPre:PresentTmp = new PresentTmp()
setPre.set()
})
```
......@@ -147,7 +154,7 @@ struct BindContentCoverDemo {
struct BindSheetDemo {
// 半模态转场高度控制变量
@State sheetHeight: number = 300;
@State sheetHeight: number|SheetSize|null|undefined = 300;
// 半模态转场控制条控制变量
@State showDragBar: boolean = true;
......@@ -190,7 +197,8 @@ struct BindSheetDemo {
build() {
Column() {
Button("Click to present sheet view")
if(this.sheetHeight){
Button("Click to present sheet view")
.onClick(() => {
// 改变状态变量,让模态界面显示
this.isPresent = !this.isPresent;
......@@ -199,6 +207,7 @@ struct BindSheetDemo {
.margin(10)
// 通过选定的半模态接口,绑定模态展示界面,style中包含两个参数,一个是设置半模态的高度,不设置时默认高度是Large,一个是是否显示控制条DragBar,默认是true显示控制条
.bindSheet($$this.isPresent, this.myBuilder(), { height: this.sheetHeight, dragBar: this.showDragBar })
}
}
.justifyContent(FlexAlign.Center)
.width('100%')
......@@ -216,6 +225,10 @@ struct BindSheetDemo {
```ts
class BMD{
value:string = ''
action:Function|undefined = undefined
}
@Entry
@Component
struct BindMenuDemo {
......@@ -227,13 +240,13 @@ struct BindMenuDemo {
action: () => {
console.info('handle Menu1 select')
}
},
} as BMD,
{
value: '菜单项2',
action: () => {
console.info('handle Menu2 select')
}
},
} as BMD,
]
build() {
......@@ -271,16 +284,18 @@ struct BindContextMenuDemo {
@Builder MyMenu() {
Row() {
Column() {
ForEach(this.num, (item: number, index: number) => {
Row() {
Text(item.toString())
.fontSize(20)
.fontColor(Color.White)
ForEach(this.num, (item: number, index?: number|undefined) => {
if(index){
Row() {
Text(item.toString())
.fontSize(20)
.fontColor(Color.White)
}
.backgroundColor(this.colors[index])
.width('100%')
.aspectRatio(2)
.justifyContent(FlexAlign.Center)
}
.backgroundColor(this.colors[index])
.width('100%')
.aspectRatio(2)
.justifyContent(FlexAlign.Center)
})
}
.width('100%')
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册