Thursday, January 26, 2023
HomeiOS DevelopmentJetpack Compose for Put on OS

Jetpack Compose for Put on OS


With Jetpack Compose for Put on OS, you’ll be able to construct stunning person interfaces for watches. It has tons of parts to select from. On this tutorial, you’ll study the entire important parts — equivalent to Inputs, Dialogs, Progress Indicators and Web page Indicators. You’ll additionally study when to make use of a Vignette and a TimeText.

Getting Began

Obtain the starter undertaking by clicking the Obtain Supplies button on the high or backside of the tutorial. Unzip it and import into Android Studio. Construct and run.

final version

The OneBreath app is a group of breath-holding instances. It additionally has a stopwatch to trace new information and save them within the assortment.

Mess around with the app to get a sense of what you’ll construct on this tutorial.

Take a look at ApneaRecordLocalSource.kt and ApneaRecordRepository.kt – these lessons mock a neighborhood information supply. It can assist to check the app, nevertheless it gained’t hold your information between app launches.

Look additionally at StopWatchViewModel.kt. That is the view mannequin for the longer term stopwatch display. It can maintain counting time.

You don’t have to vary something in these three lessons. Simply deal with the UI.

Utilizing Appropriate Dependencies

Change to the starter undertaking. Go to the app-level construct.gradle and add the next dependencies:


implementation "androidx.put on.compose:compose-material:$wear_compose_version"
implementation "androidx.put on.compose:compose-navigation:$wear_compose_version"
implementation "androidx.put on.compose:compose-foundation:$wear_compose_version"

Why do you want these? In a Put on OS app, you need to use the Put on OS variations for compose-material and compose-navigation as a result of they’re completely different from their common siblings. As for the compose-foundation library, it builds upon its common model so you’ve each dependencies.

Now that you’ve got all essential dependencies, construct and run. You’ll see the next display:

start screen

Time to dive in!

Watching over the Navigation

To start, you’ll add Compose navigation so you’ll be able to navigate between screens.

Navigating Compose for Put on OS

Navigation in Compose for Put on OS is loads just like the common Compose navigation.

Open MainActivity.kt and declare a NavHostController above apneaRecordLocalSource:


non-public lateinit var navController: NavHostController

In setContent() above OneBreathTheme(), initialize a swipeDismissableNavController:


navController = rememberSwipeDismissableNavController()

The distinction between Put on OS and an everyday app is in how the person navigates again. Since watches don’t have again buttons, navigation again occurs when customers swipe to dismiss. That’s why you’ll use a SwipeDissmissableNavHost() right here.

Contained in the OneBreathTheme(), change the non permanent Field() composable with the entry level to the app:


OneBreathApp(
  swipeDismissableNavController = navController,
  apneaRecordRepository = apneaRecordRepository
)

Right here, you move the just lately created navController and the repository to OneBreathApp(), the place you’ll arrange the app navigation.

Go to OneBreathApp.kt. As you’ll be able to see, it makes use of Scaffold(). However in contrast to the common Compose Scaffold(), it has new attributes like timeText and vignette. You’ll get again to those later. For now, deal with SwipeDismissableNavHost(), the place you move navController and startDestination as parameters.

Take a look at the Vacation spot.kt file within the ui/navigation folder:


sealed class Vacation spot(
  val route: String
) {
  object Information : Vacation spot("information")
  object DayTrainingDetails : Vacation spot("dayTrainingDetails")
  object StopWatch : Vacation spot("stopWatch")
}

This sealed class describes all of the attainable routes within the app. Now you’ll be able to arrange navigation for these routes. In OneBreathApp.kt, change SwipeDismissableNavHost‘s empty physique with the related routes:


composable(route = Vacation spot.StopWatch.route) {
}

composable(route = Vacation spot.TrainingDayDetails.route) {
}

composable(route = Vacation spot.Information.route) {
}

Add the next inside the primary route composable:


val stopWatchViewModel = StopWatchViewModel(apneaRecordRepository)
StopWatchScreen(stopWatchViewModel)

Right here, you create a StopWatchViewModel and move it to the StopWatchScreen().

The subsequent route is Vacation spot.TrainingDayDetails. It will lead you to the TrainingDayDetailsScreen(), the place you’ll see the stats for all of the breath holds you tried on that day. In a big app, you’d create a particulars display route based mostly on the id of the merchandise you wish to show and use that id in a related DetailsViewModel. However this app is moderately easy, so you’ll be able to simply hold a reference to a particular coaching day within the OneBreathApp(). Thus, add this line above Scaffold():


var selectedDay: TrainingDay? = null

Write this code contained in the composable with Vacation spot.TrainingDayDetails:


selectedDay?.let { day ->  // 1
  TrainingDayDetailsScreen(
    day.breaths,  // 2
    onDismissed = { swipeDismissableNavController.navigateUp() }  // 3
   )
}

Right here’s what’s occurring within the code above:

  1. Navigate solely after you set the selectedDay.
  2. Solely the listing of makes an attempt is critical to show the main points.
  3. In contrast to the earlier route, you set the onDismissed() callback explicitly right here since you’re utilizing SwipeToDismissBox() in TrainingDayDetails().

HorizontalViewPager and SwipeToDismissBox Navigation

Earlier than transferring on to the following vacation spot, open TrainingDayDetailsScreen.kt. The explanation why the compose navigation in OneBreathApp.kt is completely different for this display is the SwipeToDismissBox() composable. The SwipeToDismissBox() has two states:


if (isBackground) {
  Field(modifier = Modifier.fillMaxSize())  // 1
} else {
  Field(
    modifier = Modifier
      .fillMaxSize()
      .edgeSwipeToDismiss(state)  // 2
  ) {
    HorizontalPager(state = pagerState, depend = maxPages) { web page ->
      selectedPage = pagerState.currentPage
      DetailsView(makes an attempt[page].utbTime, makes an attempt[page].totalDuration)
    }
  }
}
  1. SwipeToDismissBox() has a background scrim, which on this case is only a black full-screen field.
  2. In a standard state, this Field() composable holds a HorizontalPager, which lets you scroll by way of the main points display horizontally, but additionally makes swipe-to-dismiss motion unimaginable. That’s why it is advisable to place it inside a SwipeToDismissBox() and have the edgeSwipeToDismiss() modifier to navigate again solely when the person swipes proper within the small area on the left a part of the display.

Lastly, arrange the final navigation route: Vacation spot.Information. Again in OneBreathApp.kt in SwipeDismissableNavHost(), add the next code contained in the related composable:


RecordsListScreen(
  apneaRecordRepository.information,  // 1
  onClickStopWatch = {  // 2
    swipeDismissableNavController.navigate(
      route = Vacation spot.StopWatch.route
    )
  },
  onClickRecordItem = { day ->  // 3
    selectedDay = day
    swipeDismissableNavController.navigate(
      route = Vacation spot.TrainingDayDetails.route
    )
  }
)

Right here’s what’s occurring:

  1. The information listing display shows an inventory of information from the native supply.
  2. While you faucet the New Coaching button, it redirects you to the stopwatch display.
  3. While you select a specific coaching day from the listing, it redirects to the coaching day particulars display.

As you’ll be able to see, for the press occasions, this composable makes use of the 2 routes you’ve simply arrange.

You’re accomplished with the navigation — good job! However there’s nothing spectacular to see within the app but. So, it’s time to study in regards to the Compose UI parts for Put on OS.

Attending to Know the Parts

Open RecordsListScreen.kt and add the next to RecordsListScreen() physique:


ScalingLazyColumn {  // 1
  merchandise {
    StopWatchListItemChip(onClickStopWatch)  // 2
  }
  for (merchandise in information) {
    merchandise {
      RecordListItemChip(merchandise, onClickRecordItem)
    }
  }
}

Right here’s what this implies:

  1. ScalingLazyColumn() is a Put on OS analog for LazyColumn(). The distinction is that it adapts to the spherical watch display. Construct and refresh the previews in RecordsListScreen to get a visible illustration.
  2. Each merchandise within the ScalingLazyColumn() is a Chip(). Have a look at StopWatchListItemChip() and RecordListItemChip() — they’ve placeholders for onClick, icon, label, secondaryLabel and different parameters.

Construct and run. You’ll see a group of breath holds:

records list

You may both begin a brand new coaching or select a coaching day document from the listing after which swipe to dismiss.

Congratulations — you nailed the navigation!

Now, open StopWatchScreen.kt. This display shows the info processed within the StopWatchViewModel. On high of the StopWatchScreen() composable, there are two states that affect the recomposition:


val state by stopWatchViewModel.state.collectAsState() // 1
val length by stopWatchViewModel.length.collectAsState() // 2
  1. This state handles all elements of the UI that don’t depend on the present stopwatch time, such because the StartStopButton() or the textual content trace on high of it.
  2. The length state will set off recomposition of the progress indicator and the time textual content each second.

For now, the StopWatchScreen() solely counts the time. However as soon as the person finishes their breath maintain, the app ought to ask for a sure enter. This can be a excellent place to make use of a dialog.

Utilizing Dialogs

You should use Put on OS dialogs identical to the common Compose dialogs. Have a look at the dialog() composable in StopWatchScreen():


Dialog(
  showDialog = showSaveDialog,  // 1
  onDismissRequest = { showSaveDialog = false }  // 2
) {
  SaveResultDialog(
    onPositiveClick = {  // 3
    },
    onNegativeClick = {
    },
    consequence = length.toRecordString()
  )
}

Right here’s what’s occurring:

  1. You launched showSaveDialog on the high of StopWatchScreen(). It controls whether or not this dialog is seen or not.
  2. A easy callback resets showSaveDialog to false and hides the dialog.
  3. SaveResultDialog() is an Alert() dialog and requires onPositiveClick() and onNegativeClick() callbacks.

To activate this dialog, within the StartStopButton() discover the onStop() callback and add the code under stopWatchViewModel.cease():


if (state.utbTime > 0) {
  showSaveDialog = true
}

In freediving, the primary essential metric in your breath maintain is the Urge To Breathe (UTB) time. That is the second when the CO2 reaches a sure threshold and your mind indicators your physique to inhale. However it doesn’t imply you’ve run out of oxygen but.

Take a look at the cease() perform in StopWatchViewModel.kt. It controls what occurs when the person faucets the cease button. On the primary faucet, it saves the UTB time to a neighborhood variable. On the second faucet, time monitoring really stops. That’s why you set showSaveDialog to true solely when utbTime has already been recorded.

Construct and run. Take a deep breath and begin the stopwatch. When you faucet the button two instances — one for UTB and one for remaining time — you’ll see the SaveResultDialog dialog:

result dialog

Subsequent, you’ll add some interactive parts to this app.

Including Inputs

Go to SaveResultDialog.kt. That is an Alert, which is among the Put on OS dialog sorts. The opposite sort is Affirmation. You may study extra in regards to the variations between the 2 sorts within the official documentation.

Have a look at the parameters of Alert(). It has an optionally available icon and a title, which is already created. The physique of this alert dialog makes use of a Textual content() composable. You solely have to set the buttons for the person interplay. Set the negativeButton and positiveButton parameters to:


negativeButton = {
  Button(
    onClick = onNegativeClick,  // 1
    colours = ButtonDefaults.secondaryButtonColors()  // 2
  ) {
    Icon(
      imageVector = Icons.Stuffed.Clear,  // 3
      contentDescription = "no"
    )
  }
},
positiveButton = {
  Button(
    onClick = onPositiveClick,
    colours = ButtonDefaults.primaryButtonColors()
  ) {
    Icon(
      imageVector = Icons.Stuffed.Test,
      contentDescription = "sure"
    )
  }
}

As you’ll be able to see, utilizing Button() in Put on OS is straightforward:

  1. Crucial half is offering the buttons with an onClick callback, which you’ll set in a second.
  2. You may specify the colours for the buttons.
  3. You may as well select an icon — on this case, it’s a cross for the detrimental motion and a tick for the constructive motion.

Again within the StopWatchScreen.kt, discover SaveResultDialog() and alter the onPositiveCallback() and onNegativeCallback() to:


onPositiveClick = {
  showSaveDialog = false
  stopWatchViewModel.save()
},
onNegativeClick = {
  showSaveDialog = false
  stopWatchViewModel.refresh()
}

In each instances right here, you shut the dialog. If the person agrees to avoid wasting the consequence, you name the related technique from StopWatchViewModel. In any other case, you simply have to refresh the values proven within the StopWatchScreen().

Construct and run.

interact with dialog

You may work together with the dialog and save or discard the breath maintain consequence. Both approach, you navigate again to the StopWatchScreen().

Buttons are one option to work together with the person. There are additionally a number of enter choices in Put on OS. You should use one of many following:

  • Slider: To select from a variety of values.
  • Stepper: In order for you a vertical model of a slider.
  • Toggle chip: To modify between two values.
  • Picker: To pick particular information.

Within the OneBreath app, you’ll take care of a Slider().

Open AssessmentDialog.kt. Add the next line above the Alert(), doing all the mandatory imports:


var worth by bear in mind { mutableStateOf(5f) }

It will maintain the worth of an InlineSlider() with an preliminary worth of 5. Within the subsequent step, you’ll set the worth vary to 10.

Add the InlineSider() to the empty physique of Alert() dialog:


InlineSlider(
  worth = worth,
  onValueChange = { worth = it },
  increaseIcon = { Icon(InlineSliderDefaults.Enhance, "happy") },
  decreaseIcon = { Icon(InlineSliderDefaults.Lower, "unhappy") },
  valueRange = 1f..10f,
  steps = 10,
  segmented = true
)

As you’ll be able to see, it has a number of parameters for the worth, the buttons, the worth vary, the variety of steps and whether or not it has segments or not. The worth of this slider modifications when the person faucets the Enhance or Lower buttons. Because you wish to save this worth together with the breath maintain time outcomes, change the empty onClick parameter in positiveButton:


onClick = {
  onPositiveClick(worth)
}

And now, again in StopWatchScreen.kt, use the AssessmentDialog() identical to you probably did with SaveResultDialog(). First, add a variable under showSaveDialog:


var showRatingDialog by bear in mind { mutableStateOf(false) }

Then, on the backside of StopWatchScreen() add a dialog. Use the showRatingDialog as a deal with to indicate or disguise the dialog and use AssessmentDialog() as content material:


Dialog(
  showDialog = showRatingDialog,
  onDismissRequest = { showRatingDialog = false }
) {
  AssessmentDialog(
    onPositiveClick = { ranking ->
      showRatingDialog = false
      stopWatchViewModel.save(ranking)  // 1
    },
    onNegativeClick = {
      showRatingDialog = false
      stopWatchViewModel.save()  // 2
    }
  )
}

Right here’s what occurs:

  1. After tapping the constructive button, you save the self-rating within the database together with different values from the StopWatchViewModel.
  2. When the person doesn’t wish to price himself, you simply save the consequence.

Additionally, change stopWatchViewModel.save() in SaveResultDialog() with showRatingDialog = true, since you wish to present one dialog after one other and save the consequence solely after the AssessmentDialog().

Construct and run. For those who selected to maintain the document within the first dialog, you’ll see the second dialog as properly:

slider dialog
Prepared for some even cooler Put on OS Composables? It’s time to speak about Vignette and TimeText.

Including a Vignette

Open OneBreathApp.kt and take a look at the parameters in Scaffold() once more.
Set vignette parameter to:


vignette = {
  if (currentBackStackEntry?.vacation spot?.route == Vacation spot.Information.route) {
    Vignette(vignettePosition = VignettePosition.TopAndBottom)
  }
}

This situation means the vignette shall be there just for the RecordsListScreen(). A vignette is a UI characteristic that dims an edge a part of the display. In your case, it’s TopAndBottom, as laid out in vignettePosition.

Evaluate the document listing display with and with out the vignette:

With out Vignette With Vignette
no vignette with vignette

See the distinction? Within the right-hand model, the sides are barely darker.

TimeText

One other important Put on OS UI element is TimeText(). Nonetheless in OneBreathApp.kt, change the empty timeText parameter in Scaffold() with:


timeText = {
  if (currentBackStackEntry?.vacation spot?.route == Vacation spot.TrainingDayDetails.route) {  // 1
    TimeText(
      startLinearContent = {  // 2
        Textual content(
          textual content = selectedDay?.date.toFormattedString(),
          shade = colorPrimary,
          type = textStyle
        )
      },
      startCurvedContent = {  // 3
        curvedText(
          textual content = selectedDay?.date.toFormattedString(),
          shade = colorPrimary,
          type = CurvedTextStyle(textStyle)
        )
      }
    )
  } else TimeText()  // 4
}

Right here’s a breakdown of this code:

  1. You solely wish to present an extra textual content earlier than the time within the coaching day particulars display. This extra textual content will maintain the date of the document.
  2. TimeText() adapts to spherical and sq. watches. For sq. watches, it makes use of TimeTextDefaults.timeTextStyle().
  3. For spherical watches, use CurvedTextStyle().
  4. All of the screens besides the coaching day particulars display will nonetheless present the present time on high.

Construct and run. You’ll see the present time on high now. Faucet on one of many inexperienced chips. Within the coaching day particulars display, you’ll additionally see the date:

training day details screen

Progress Indicator

Wouldn’t it’s good to have one thing like a clock hand for the stopwatch? You are able to do that with a Put on OS CircularProgressIndicator.

Go to StopWatchScreen.kt and add the next to the highest of the Field(), proper above Column():


CircularProgressIndicator(
  progress = length.toProgress(),
  modifier = Modifier
    .fillMaxSize()
    .padding(all = 1.dp)
)

This indicator will recompose each second and present the present length of your breath maintain. It’s normally really helpful to go away a niche for the TimeText() by including startAngle and endAngle parameters, however in OneBreath you’ll sacrifice these to make the indicator resemble a clock hand.

Construct and run the app and begin the stopwatch. You’ll see the clock ticking:

determinate progress indicator

This CircularProgressIndicator() is determinate, however you too can use its indeterminate model to indicate a loading indicator – simply omit the progress parameter. It will seem like this:

indeterminate progress indicator

Web page Indicator

Whilst you’re nonetheless operating the app, go to the document listing display and faucet on one of many coaching day objects. Right here, within the particulars display, you’ll be able to web page by way of all of your breath holds on that day. Can be good to know what web page you’re on, proper? A HorizontalPageIndicator will show you how to with that.

Go to TrainingDayDetailsScreen.kt. In SwipeToDismissBox(), add this under val pagerState = rememberPagerState() :


val pageIndicatorState: PageIndicatorState = bear in mind {
  object : PageIndicatorState {
    override val pageOffset: Float
      get() = 0f
    override val selectedPage: Int
      get() = selectedPage
    override val pageCount: Int
      get() = maxPages
  }
}

Right here, you create a PageIndicatorState that connects the HorizontalPager() and HorizontalPageIndicator(). The selectedPage is ready once you scroll by way of the pager. The pageCount is the entire variety of makes an attempt on the coaching day. The pageOffset is 0f on this case, however you need to use it to animate the indicator.

To make use of it, add HorizontalPageIndicator() proper under HorizontalPager:


HorizontalPageIndicator(
  pageIndicatorState = pageIndicatorState,
  selectedColor = colorAccent
)

Construct and run. Decide a coaching day from the listing. You’ll see a paging indicator on the backside:

paging indicator

HorizontalPageIndicator() is an instance of a horizontal paging indicator. For those who want a vertical indicator, you need to use a PositionIndicator(). Take a look at the official supplies for extra parts.

The place to Go From Right here?

Obtain the finished undertaking recordsdata by clicking the Obtain Supplies button on the high or backside of the tutorial.

Congratulations! Now you can observe your breath-holding information with the app you’ve simply constructed. Now, take a deep breath and set a brand new private document! :]

For those who’re concerned with studying extra about varied Put on OS Composables, try the official documentation documentation, in addition to the Horologist library for superior date and time pickers. And in the event you take pleasure in Put on OS growth, don’t miss out on the Creating Tiles for Put on OS video course.

We hope you loved this tutorial. When you have any questions or feedback, please be part of the discussion board dialogue under!



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments