Implementing Responsive Layouts in ArkUI with Grid, Flex, and Media Queries
ArkUI provides several methods for building responsive user interfaces. This guide demonstrates three primary approaches using the classic "Hello World" example as a base.
Using Grid and GridItem Components
The Grid and GridItem components offer a straightforward way to create responsive grids. Breakpoints and span properties control layout adjustments.
import { Grid, GridItem, Text } from 'arkui';
@Entry
@Component
struct MainPage {
@State greetingText: string = 'Hello World';
build() {
return (
<Grid>
<GridItem colSpan={12} rowSpan={1} breakpoint="sm">
<Text(this.greetingText)
.fontSize(50)
.fontWeight(FontWeight.Bold) />
</GridItem>
<GridItem colSpan={6} rowSpan={2} breakpoint="md">
<Text(this.greetingText)
.fontSize(50)
.fontWeight(FontWeight.Bold) />
</GridItem>
<GridItem colSpan={4} rowSpan={3} breakpoint="lg">
<Text(this.greetingText)
.fontSize(50)
.fontWeight(FontWeight.Bold) />
</GridItem>
</Grid>
);
}
}
In this example, GridItem components use colSpan, rowSpan, and breakpoint properties to define different grid layouts for small (sm), medium (md), and large (lg) viewports.
Using Flex Component for Flexible Layouts
Flexbox provides control over alignment, direction, and order of child elements, with responsive display properties.
import { Flex, Text } from 'arkui';
@Entry
@Component
struct MainPage {
@State greetingText: string = 'Hello World';
build() {
return (
<Flex direction="column" justify="center" align="center">
<Flex.Item flex={[1, 2]} display={['none', 'block']}>
<Text(this.greetingText)
.fontSize(50)
.fontWeight(FontWeight.Bold) />
</Flex.Item>
<Flex.Item flex={1} display={['block', 'none']}>
<Text(this.greetingText)
.fontSize(50)
.fontWeight(FontWeight.Bold) />
</Flex.Item>
</Flex>
);
}
}
Here, the Flex container is set for vertical, centered alignment. The first Flex.Item hides on small screens (display: 'none') and takes two fractional units on larger ones. The second item behaves inversely.
Using Media Queries with StyleSheet
Media queries allow for fine-grained style changes based on viewport dimensions directly within a stylesheet.
import { Text, StyleSheet } from 'arkui';
@Entry
@Component
struct MainPage {
@State greetingText: string = 'Hello World';
build() {
return (
<Text style={styles.responsiveText}>
{this.greetingText}
</Text>
);
}
}
const styles = StyleSheet.create({
responsiveText: {
fontSize: 50,
fontWeight: 'bold',
textAlign: 'center',
'@media (max-width: 600px)': {
fontSize: 30,
},
'@media (min-width: 601px) and (max-width: 1200px)': {
fontSize: 40,
},
'@media (min-width: 1201px)': {
fontSize: 50,
},
},
});
This approach defines a base style for the Text component and uses @media rules to adjust the fontSize property across three common breakpoints.