Location>code7788 >text

Hongmeng NEXT Development Case: World Timetable

Popularity:988 ℃/2024-12-16 20:09:48

 

[Introduction]

This case will show how to develop a simple World Clock application using the Hongmeng NEXT framework. The application is able to display the current time of multiple cities and support search function, which is convenient for users to quickly find the time information of the desired city. In this article, we will introduce the idea of application implementation in detail, including how to get the time zone information, update the time of the city, and how to realize the search highlighting function.

[Environmental Preparation]

- Operating system: Windows 10

- Development Tools: DevEco Studio NEXT Beta1 Build Version: 5.0.3.806

- Target device: Huawei Mate60 Pro

- Development language: ArkTS

- Framework: ArkUI

- API version: API 12

[Realization Ideas]

1. Component architectural design

Our application consists of two core components: the CityTimeInfo class, which stores the name, current time and time zone of each city, and the WorldClockApp component, which manages the list of city times, the search function and the user interface.

2. Obtaining time zone information

When the application starts, we need to get the available time zone information. By calling the () method, we can get all the available time zone IDs. next, we use these IDs to create a CityTimeInfo instance and add it to the list of city times. To make sure the user can see the current time, we also add the time information for Beijing as the default city.

3. Update time logic

In order to update the current time of the city in real time, we implement the time update logic in the updateAllCityTimes method. By getting the system's locale and the corresponding calendar object, we can get the current year, month, day, hour, minute, and second based on the city's time zone ID and format it as a string. This method will be called once per second when the page is displayed to ensure the accuracy of the time information.

4. Search function implementation

In order to enhance the user experience, we have implemented a search function that allows users to filter cities by entering keywords. In the highlightSearchText method, we segment the city names and highlight the matching keywords. In this way, users can quickly find the desired city and the highlighted text provides better visual feedback.

5. User interface construction

Finally, we build the user interface using the build method. The interface consists of a search box, a display area for the city name and the time. We use the Column and Row components for layout and beautify the interface by setting style properties. The scrolling area is implemented so that the user can easily navigate through the information of multiple cities.

[complete code]

import { i18n } from '@' // Import internationalization module for handling multiple languages
import { inputMethod } from '@' // Importing Input Method Modules

@ObservedV2
  // Observer decorator for observing state changes
class CityTimeInfo { // Define the city time information class
  @Trace cityName: string = ""; // City name, initially empty string
  @Trace currentTime: string = ""; // Current time, initially empty string
  timeZone: ; // Time zone properties

  constructor(cityName: string, timeZone: ) { // Constructor to receive city name and time zone
     = cityName; // Set the city name
     = timeZone; // Setting the time zone
  }

  @Trace isVisible: boolean = true; // Whether or not it's visible, initially true
}

@Entry
  // Entry component decorator
@Component
  // Component Decorator
struct WorldClockApp { // Define the World Clock application component
  @State private searchText: string = ''; // Search for text, initially empty string
  @State private cityTimeList: CityTimeInfo[] = []; // List of city time information, initially empty array
  private lineColor: string = "#e6e6e6"; // border color
  private titleBackgroundColor: string = "#f8f8f8"; // Title background color
  private textColor: string = "#333333"; // text color
  private basePadding: number = 4; // Inside Margin
  private lineWidth: number = 2; // Border width
  private rowHeight: number = 50; // Row height
  private ratio: number[] = [1, 1]; // Column width ratio
  private textSize: number = 14; // Base font size
  private updateIntervalId = 0; // Update interval ID

  updateAllCityTimes() { // Update the time in all cities
    const locale = (); // Get the system locale
    for (const cityTime of ) { // Traverse the list of city times
      const timeZoneId: string = (); // Get the time zone ID
      const calendar = (locale); // Get the calendar object
      (timeZoneId); // Set the time zone for the calendar

      // Get the parts of the current time
      const year = ("year").toString().padStart(4, '0'); // Year
      const month = ("month").toString().padStart(2, '0'); // Months
      const day = ("date").toString().padStart(2, '0'); // Day
      const hour = ("hour_of_day").toString().padStart(2, '0'); // hour
      const minute = ("minute").toString().padStart(2, '0'); // Minutes
      const second = ("second").toString().padStart(2, '0'); // seconds

      // Update the current time string for the city
       = `${year}surname Nian${month}moon${day}date ${hour}:${minute}:${second}`;
    }
  }

  onPageShow(): void { // Processing of the page as it is displayed
    clearInterval(); // Clear the previous timer
     = setInterval(() => { // Setting a new timer
      (); // Updates the time in all cities every second
    }, 1000);
  }

  onPageHide(): void { // Handling when the page is hidden
    clearInterval(); // Clear the timer
  }

  private highlightSearchText(cityTime: CityTimeInfo, keyword: string) { // Highlight search text
    let text =  // Get the city name

    if (!keyword) { // If there are no keywords
       = true // Set the city to be visible
      return [text] // Return city name
    }
    let segments: string[] = []; // Store segmented text
    let lastMatchEnd: number = 0; // Where the last match ended
    while (true) { // Loop over keywords
      const matchIndex = (keyword, lastMatchEnd); // Find keyword locations
      if (matchIndex === -1) { // If not found
        ((lastMatchEnd)); // Add remaining text
        break; // Exit the loop
      } else {
        ((lastMatchEnd, matchIndex)); // Add pre-match text
        ((matchIndex, matchIndex + )); // Add matching keywords
        lastMatchEnd = matchIndex + ; // Update the last match end position
      }
    }
     = ((keyword) != -1) // Setting city visibility
    return segments; // Return segmented text
  }

  aboutToAppear() { // Handling of components when they are about to appear
    const timeZoneIds: Array<string> = (); // Get a list of available time zone IDs

    (new CityTimeInfo('Beijing, capital of People's * (sino)', ())); // Add city time information for Beijing

    for (const id of timeZoneIds) { // Iterate over time zone IDs
      const cityDisplayName = (('/')[1], "zh-CN"); // Get the city display name
      if (cityDisplayName) { // If the city name exists
        (new CityTimeInfo(cityDisplayName, (id))); // Add city time information
      }
    }

    (); // Update the time in all cities
  }

  build() { // Build the component's UI
    Column({ space: 0 }) { // Create a vertical column
      Search({ value: $$ })// Create a search box
        .margin()// Setting the margins
        .fontFeature("\"ss01\" on") // Setting font characteristics
      Column() { // Create a column
        Row() { // Create a line
          Text('The City')// Display "City" text
            .height('100%')// Height occupied
            .layoutWeight([0])// Setting Layout Weights
            .textAlign()// Text centering
            .fontSize()// Setting the font size
            .fontWeight(600)// Set the font thickness
            .fontColor() // Set the font color
          Line().height('100%').width().backgroundColor() // Create separator lines
          Text('Time')// Display "time" text
            .height('100%')// Height occupied
            .layoutWeight([1])// Setting Layout Weights
            .textAlign()// Text centering
            .fontSize()// Setting the font size
            .fontWeight(600)// Set the font thickness
            .fontColor() // Set the font color
        }.height().borderWidth().borderColor() // Setting line height and borders
        .backgroundColor() // Setting the background color
      }.width(`100%`).padding({ left: , right:  }) // Set column widths and inner margins

      Scroll() { // Create scrollable areas
        Column() { // Create a column
          ForEach(, (item: CityTimeInfo) => { // Traverse the list of city times
            Row() { // Create a line
              Text() { // Create text
                ForEach((item, ), (segment: string, index: number) => { // Highlight search text
                  ContainerSpan() { // Create the container
                    Span(segment)// Create text segments
                      .fontColor(segment ===  ?  : )// Set the font color
                      .onClick(() => { // Click event
                        (`Highlighted text is clicked:${segment}`); // Output the clicked text
                        (`Click on the index:${index}`); // Output the index of the click
                      });
                  }.textBackgroundStyle({
                    // Set the text background style
                    color: segment ===  ?  :  // Set the background color based on whether it matches or not
                  });
                });
              }
              .height('100%') // Height occupied
              .layoutWeight([0]) // Setting Layout Weights
              .textAlign() // Text centering
              .fontSize() // Setting the font size
              .fontColor() // Set the font color

              Line().height('100%').width().backgroundColor() // Create separator lines
              Text()// Display the current time
                .height('100%')// Height occupied
                .layoutWeight([1])// Setting Layout Weights
                .textAlign()// Text centering
                .fontSize()// Setting the font size
                .fontColor() // Set the font color
            }
            .height() // Set the line height
            .borderWidth({ left: , right: , bottom:  }) // Set the border width
            .borderColor() // Set the border color
            .visibility( ?  : ) // Setting the display status according to visibility
          })

        }.width(`100%`).padding({ left: , right:  }) // Set the width and inner margins
      }
      .width('100%') // Set the width to be full
      .layoutWeight(1) // Setting Layout Weights
      .align() // Alignment
      .onScrollStart(() => { // Scroll start event
        () // Page Hide Handling
      })
      .onScrollStop(() => { // Scroll stop event
        () // Page display processing
      })
      .onTouch((event) => { // Touch events
        if ( == ) { // If it's a press event
          ().stopInputSession() // Stop the input session
        }
      })
    }
  }
}