Текстовые часы в Android с помощью Jetpack Compose
Текстовые часы — это виджет пользовательского интерфейса в Android, который используется для отображения текущего времени в приложениях Android. Этот виджет отображает текущее время в простом текстовом представлении. Виджет текстовых часов отображает время в 12- и 24-часовом формате. В этой статье мы рассмотрим Как использовать виджет TextClock на Android с помощью Jetpack Compose .
Пошаговая реализация
Шаг 1. Создайте новый проект в Android Studio.
Чтобы создать новый проект в Android Studio, обратитесь к разделу «Как создать/запустить новый проект в Android Studio». При выборе шаблона выберите «Пустая активность создания» . Если вы не найдете этот шаблон, попробуйте обновить Android Studio до последней версии. Мы продемонстрировали приложение на Kotlin, поэтому убедитесь, что вы выбрали Kotlin в качестве основного языка при создании нового проекта.
Шаг 2: Добавление нового цвета в файл Color.kt
Перейдите к приложению > java > имени пакета вашего приложения > ui.theme > файлу Color.kt и добавьте в него приведенный ниже код.
Kotlin
package com.example.newcanaryproject.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFF0F9D58)val Purple500 = Color(0xFF0F9D58)val Purple700 = Color(0xFF3700B3)val Teal200 = Color(0xFF03DAC5) // on below line we are adding different colors.val greenColor = Color(0xFF0F9D58) |
Шаг 3: Работа с файлом MainActivity.kt
Перейдите к файлу MainActivity.kt и обратитесь к следующему коду. Ниже приведен код файла MainActivity.kt. Комментарии добавляются внутри кода, чтобы понять код более подробно.
Kotlin
package com.example.newcanaryproject import android.Manifest.permission.READ_EXTERNAL_STORAGEimport android.app.Activityimport android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport android.content.IntentFilterimport android.content.pm.PackageManagerimport android.content.res.ColorStateListimport android.database.Cursorimport android.os.Bundleimport android.os.Environmentimport android.provider.MediaStoreimport android.util.Logimport android.widget.TextClockimport android.widget.Toastimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.ExperimentalFoundationApiimport androidx.compose.foundation.Imageimport androidx.compose.foundation.layout.*import androidx.compose.foundation.lazy.GridCellsimport androidx.compose.foundation.lazy.LazyVerticalGridimport androidx.compose.material.*import androidx.compose.runtime.*import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.colorResourceimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.semantics.Role.Companion.Imageimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.unit.*import androidx.compose.ui.viewinterop.AndroidViewimport androidx.core.app.ActivityCompatimport androidx.core.app.ActivityCompat.requestPermissionsimport androidx.core.content.ContextCompatimport androidx.localbroadcastmanager.content.LocalBroadcastManagerimport coil.compose.rememberImagePainterimport com.example.newcanaryproject.MainActivity2import com.example.newcanaryproject.Rimport com.example.newcanaryproject.ui.theme.*import java.io.File class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { NewCanaryProjectTheme { // on below line we are specifying // background color for our application Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { // on below line we are specifying theme as scaffold. Scaffold( // in scaffold we are specifying top bar. topBar = { // inside top bar we are specifying background color. TopAppBar(backgroundColor = greenColor, // along with that we are specifying title for our top bar. title = { // in the top bar we are specifying tile as a text Text( // on below line we are specifying text // to display in top app bar. text = "GFG", // on below line we are specifying modifier // to fill max width. modifier = Modifier.fillMaxWidth(), // on below line we are specifying // text alignment. textAlign = TextAlign.Center, // on below line we are // specifying color for our text. color = Color.White ) }) }) { // on below line we are calling // display text clock function. displayTxtClock() } } } } }} // on below line we are creating // a function for our text clock.@Composablefun displayTxtClock() { // on below line we are creating // a column on below sides. Column( // on below line we are adding padding // padding for our column and filling the max size. Modifier .fillMaxSize() .fillMaxHeight() .fillMaxWidth(), // on below line we are adding // horizontal alignment for our column horizontalAlignment = Alignment.CenterHorizontally, // on below line we are adding // vertical arrangement for our column verticalArrangement = Arrangement.Center ) { Text( // on below line we are specifying text // to display in top app bar. text = "Text Clock in Android", // on below line we are specifying // modifier to fill max width. modifier = Modifier.fillMaxWidth(), // on below line we are // specifying text alignment. textAlign = TextAlign.Center, // on below line we are // specifying color for our text. color = greenColor, // on below line we are // updating font size. fontSize = 25.sp, ) // on below line we are creating a spacer. Spacer(modifier = Modifier.height(20.dp)) // on below line we are creating a text clock. AndroidView( // on below line we are initializing our text clock. factory = { context -> TextClock(context).apply { // on below line we are setting 12 hour format. format12Hour?.let { this.format12Hour = "hh:mm:ss a" } // on below line we are setting time zone. timeZone?.let { this.timeZone = it } // on below line we are setting text size. textSize.let { this.textSize = 30f } } }, // on below line we are adding padding. modifier = Modifier.padding(5.dp), ) }} |
Теперь запустите ваше приложение, чтобы увидеть результат.
Выход: