[Daily HarmonyOS Next Knowledge] URL Encoding, Resource Adaptation, Routing Mixing, Custom Root Container, News-related Examples
1. HarmonyOS encodeURIComponent?
How to implement similar functionality: const imgParams = encodeURIComponent(imgBase64Str)
String encoding demo:
@Entry
@Component struct Index {
@State message: string = 'Hello World';
name: string = "张三";
build() {
Row() {
Column() {
Text(this.message)
.fontSize(25)
.fontWeight(FontWeight.Bold)
Button({
type: ButtonType.Capsule,
margin: { bottom: 20 }
}) {
Text('encodeURIComponent')
.fontSize(25)
}
.onClick(() => {
this.message = "http://example.com/index.html?url=" + encodeURIComponent("http://example.com?name=" + this.name);
})
Button({
type: ButtonType.Capsule,
margin: { bottom: 20 }
}) {
Text('encodeURI')
.fontSize(25)
}
.onClick(() => {
this.message = encodeURI("http://example.com/index.html?name=" + this.name);
})
}
.width('100%')
}
.height('100%')
}
}
2. HarmonyOS resource adaptation?
If only one set of float resources is defined in the resources directory, do references to these resources need to be converted to the corresponding dimensions for mobile devices?
- If there is only one set of UI resources, the adaptation of width/height in formal projects requires manual conversion decisions, as the system does not automatically convert based on mobile device dimensions.
- For better adaptation without conversion, consider:
- Using
vpfor pixel units,fpfor text, and responsive layouts. - Using
designWidthto define the design baseline width, then scaling elements based on the actual device width.
- Using
Virtual pixel unit (vp):
Virtual pixels provide a flexible way to adapt to different screen densities, differing from hardware pixel units.
Font pixel unit (fp):
Fp is identical to vp by default (1fp = 1vp). If users enable larger fonts in settings, fp scales by the system font ratio (1fp = 1vp * scale).
Best practices:
- Use
fpfor text (default unit ispx, which may cause layout deviations on different devices;fphandles screen density automatically). - Use
vpfor distance units (similar tosp/dpin other frameworks). -
vpis unaffected bydesignWidthconfiguration, whilelpxis scaled based ondesignWidth.- Example: If
designWidthis changed from 720 to 750, a container with720lpxwidth will: - Fill the screen when
designWidth: 720. - Not fill the screen when
designWidth: 750.
- Example: If
3. Can HarmonyOS Navigation and router be used mixedly?
Navigation and router can be used mixedly with specific restrictions and recommended strategies:
-
router use cases:
- Suitable for simple page jumps without complex animations, interactions, or multi-level routing.
- Ideal for scenarios requiring UIContext of the main window for navigation.
-
Navigation use cases:
- Suitable for complex scenarios needing to replace router capabilities, offering more robust routing and navigation features.
- Handles complex interaction logic and multi-level routing requirements.
-
Mixed usage strategies:
-
Recommendation: Use
routerfor simple scenarios; useNavigationfor complex needs to ensure consistency and user experience. -
Evolution:
routerwill continue to be maintained, but new routing features will prioritizeNavigation.
-
Recommendation: Use
-
Mixed usage restrictions:
- When using
Navigation, pay attention to details like hiding the title bar (hideTitleBar) and handling large icons. - Ensure routing consistency and correctness to avoid errors.
- When using
4. How to define a root container in HarmonyOS?
How to define a root component/container similar to Column/Row?
ArkTS supports TypeScript decorator syntax prior to TS5.0. For decorator definitions and runtime behavior, refer to the TS official documentation. Note that decorators defined in .ets files must comply with ArkTS syntax (e.g., no any types).
Decorator examples (class, property, method, parameter):
function TestClassDecorator(target: Function) {}
function TestMemberDecorator(target: testClass, memberName: String) {}
function TestFunDecorator(target: testClass, propertyName: String, descriptor: PropertyDescriptor) {}
function TestArgDecorator(target: Function, methodName: String, paramIndex: Number) {}
@TestClassDecorator
class testClass {
@TestMemberDecorator
count: number = 123;
@TestFunDecorator
TestFun(@TestArgDecorator param: string) {}
}
Root container demo with decorators:
import { MyDescriptor } from ‘…/common/decorators’
@Entry
@Component
struct Index_231129191721035 {
@State message: string = ‘Hello World’;
aboutToAppear() {
this.demo()
}
build() {
Flex() {
// Content
}
.backgroundColor(Color.Green)
.constraintSize({
minWidth: 100,
maxWidth: 200,
minHeight: 0,
maxHeight: 200
})
.height(‘100%’)
}
@MyDescriptor
demo() {
console.log(‘ccc’)
return ‘cccc’
}
}
export function MyDescriptor(target: Object, key: string, descriptor: PropertyDescriptor) {
const originalMethod: Function = descriptor.value;
descriptor.value = (...args: Object[]) => {
console.log(`Calling ${target.constructor.name} method ${key} with argument: ${args}`);
const result: Object = originalMethod(...args);
console.log(`Method ${key} returned: ${result}`);
return result;
}
return descriptor;
}
Note: A class decorated by a decorator (e.g., class A) requires new A() to trigger the decorator.
5. HarmonyOS news-related demo reference?
Refer to UI Framework - Multi-news Reading.
Media news interface (repeating layout):
- Uses grid layout, controlling column count via breakpoints.
- The
onBreakChangecallback ofGridRowupdates breakpoints and data source counts when the interface size changes. -
columns = 1forsm/mdbreakpoints;columns = 2forlgand above.
News channel interface (repeating layout):
- Similarly uses grid layout with column count controlled by breakpoints.
- For
sm/mdbreakpoints:columns = 1, hide news summaries; forlgand above:columns = 2, display summaries with max 2 lines and ellipsis.
News list interface (list to grid conversion):
- Uses
Listforsmbreakpoints; uses grid layout for breakpoints abovesm. -
mdbreakpoint: 2 columns;lgbreakpoint: 4 columns, withGridColwidth adjusted as needed.


Top comments (0)