Мое приложение начинается здесь...
@Composable
fun OnBoarding(navController: NavController, viewModel: FirstTimeViewModel) {
val isFirstTime by viewModel.isFirstTime.collectAsStateWithLifecycle()
Surface(color = MaterialTheme.colorScheme.onPrimary) {
when (isFirstTime) {
null -> {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator(
color = Color.Blue
)
}
}
true -> {
// First time launch
OnBoardingScreenHorizontalPager(navController)
}
else -> {
// Non-first time launch
NonFirstTimeContent()
}
}
}
}
Теперь OnBoarding Screen HorizontalPager вызывает серию составных объектов и, наконец, достигает составного объекта
@Composable
fun RegisterName(
viewModel: FirstTimeViewModel
) {
Column(
modifier = Modifier
.fillMaxSize()
.background(Color.White)
) {
var nickname by remember { mutableStateOf("") }
var isEulaAgreed by remember { mutableStateOf(false) }
val context = LocalContext.current
// some logic to change isEulaAgreed and nickname has been omited
Box(
modifier = Modifier
.fillMaxSize()
.background(colorResource(id = R.color.white))
) {
Column(
modifier = Modifier
.fillMaxSize()
.background(colorResource(id = R.color.white))
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
Button(
onClick = {
val message = when {
!isEulaAgreed -> "Please Accept Terms and Conditions"
nickname.length < 2 -> "Entered name must be at least 2 characters"
else -> null
}
message?.let {
Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
}
if (isEulaAgreed && nickname.length >= 2) {
viewModel.onFirstTime()
}
},
shape = RoundedCornerShape(26.dp),
colors = ButtonDefaults.buttonColors(
containerColor = if (isEulaAgreed) colorResource(id = R.color.onboarding_green) else colorResource(
id = R.color.unchecked_button
)
),
modifier = Modifier
.width(200.dp)
.height(50.dp)
) {
Text(
text = stringResource(id = R.string.continue_registration),
fontFamily = montserratFamily,
fontWeight = FontWeight.W800,
color = if (isEulaAgreed) colorResource(id = R.color.white) else colorResource(
id = R.color.unchecked_text
)
)
}
}
}
}
После нажатия кнопки ничего не происходит, но после того, как я перезапускаю приложение после закрытия, оно попадает в составную функцию NonFirstTimeContent() из Onboarding Composable. Как сделать это мгновенно?
здесь также код обработки хранилища данных
// SettingsDataStoreManager.kt
private val Context.dataStore: DataStore
by preferencesDataStore(name = "settings")
class SettingsDataStoreManager(context: Context) {
private val dataStore = context.dataStore
suspend fun setFirstTime(isFirstTime: Boolean) {
dataStore.edit { preferences ->
preferences[isFirstTimeLaunchKey] = isFirstTime
}
}
fun isFirstTimeLaunch(): Flow =
dataStore.data.map { pref ->
pref[isFirstTimeLaunchKey] ?: true
}
companion object {
private val isFirstTimeLaunchKey = booleanPreferencesKey("isFirstTime")
}
}
// FirstTimeViewModel.kt
class FirstTimeViewModel(application: Application) : AndroidViewModel(application) {
private val dataStore = SettingsDataStoreManager(application)
val isFirstTime: StateFlow = dataStore.isFirstTimeLaunch()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(),
initialValue = null,
)
fun onFirstTime() {
viewModelScope.launch {
dataStore.setFirstTime(false)
}
}
}
Изменить: подключение Navhost, который вызывается из MainActivity
@Composable
fun SetupNavGraph(
navController: NavHostController,
promptManager: BiometricAuthentication
) {
NavHost(
navController = navController,
startDestination = Screens.Onboarding.route
) {
composable(route = Screens.Onboarding.route) {
OnBoarding(navController = navController, viewModel = viewModel())
}
composable(route = Screens.OnboardingRegistration.route){
RegisterUserPage(navController = navController, promptManager = promptManager)
}
composable(route = Screens.RegisterName.route)
){
RegisterName(navController = navController, password = password, isBiometricEnabled = isBiometricEnabled, viewModel = viewModel())
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... -instantly
Первый контент не запускается мгновенно ⇐ Android
Форум для тех, кто программирует под Android
1735370139
Anonymous
Мое приложение начинается здесь...
@Composable
fun OnBoarding(navController: NavController, viewModel: FirstTimeViewModel) {
val isFirstTime by viewModel.isFirstTime.collectAsStateWithLifecycle()
Surface(color = MaterialTheme.colorScheme.onPrimary) {
when (isFirstTime) {
null -> {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator(
color = Color.Blue
)
}
}
true -> {
// First time launch
OnBoardingScreenHorizontalPager(navController)
}
else -> {
// Non-first time launch
NonFirstTimeContent()
}
}
}
}
Теперь OnBoarding Screen HorizontalPager вызывает серию составных объектов и, наконец, достигает составного объекта
@Composable
fun RegisterName(
viewModel: FirstTimeViewModel
) {
Column(
modifier = Modifier
.fillMaxSize()
.background(Color.White)
) {
var nickname by remember { mutableStateOf("") }
var isEulaAgreed by remember { mutableStateOf(false) }
val context = LocalContext.current
// some logic to change isEulaAgreed and nickname has been omited
Box(
modifier = Modifier
.fillMaxSize()
.background(colorResource(id = R.color.white))
) {
Column(
modifier = Modifier
.fillMaxSize()
.background(colorResource(id = R.color.white))
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
Button(
onClick = {
val message = when {
!isEulaAgreed -> "Please Accept Terms and Conditions"
nickname.length < 2 -> "Entered name must be at least 2 characters"
else -> null
}
message?.let {
Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
}
if (isEulaAgreed && nickname.length >= 2) {
viewModel.onFirstTime()
}
},
shape = RoundedCornerShape(26.dp),
colors = ButtonDefaults.buttonColors(
containerColor = if (isEulaAgreed) colorResource(id = R.color.onboarding_green) else colorResource(
id = R.color.unchecked_button
)
),
modifier = Modifier
.width(200.dp)
.height(50.dp)
) {
Text(
text = stringResource(id = R.string.continue_registration),
fontFamily = montserratFamily,
fontWeight = FontWeight.W800,
color = if (isEulaAgreed) colorResource(id = R.color.white) else colorResource(
id = R.color.unchecked_text
)
)
}
}
}
}
После нажатия кнопки ничего не происходит, но после того, как я перезапускаю приложение после закрытия, оно попадает в составную функцию NonFirstTimeContent() из Onboarding Composable. Как сделать это мгновенно?
здесь также код обработки хранилища данных
// SettingsDataStoreManager.kt
private val Context.dataStore: DataStore
by preferencesDataStore(name = "settings")
class SettingsDataStoreManager(context: Context) {
private val dataStore = context.dataStore
suspend fun setFirstTime(isFirstTime: Boolean) {
dataStore.edit { preferences ->
preferences[isFirstTimeLaunchKey] = isFirstTime
}
}
fun isFirstTimeLaunch(): Flow =
dataStore.data.map { pref ->
pref[isFirstTimeLaunchKey] ?: true
}
companion object {
private val isFirstTimeLaunchKey = booleanPreferencesKey("isFirstTime")
}
}
// FirstTimeViewModel.kt
class FirstTimeViewModel(application: Application) : AndroidViewModel(application) {
private val dataStore = SettingsDataStoreManager(application)
val isFirstTime: StateFlow = dataStore.isFirstTimeLaunch()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(),
initialValue = null,
)
fun onFirstTime() {
viewModelScope.launch {
dataStore.setFirstTime(false)
}
}
}
Изменить: подключение Navhost, который вызывается из MainActivity
@Composable
fun SetupNavGraph(
navController: NavHostController,
promptManager: BiometricAuthentication
) {
NavHost(
navController = navController,
startDestination = Screens.Onboarding.route
) {
composable(route = Screens.Onboarding.route) {
OnBoarding(navController = navController, viewModel = viewModel())
}
composable(route = Screens.OnboardingRegistration.route){
RegisterUserPage(navController = navController, promptManager = promptManager)
}
composable(route = Screens.RegisterName.route)
){
RegisterName(navController = navController, password = password, isBiometricEnabled = isBiometricEnabled, viewModel = viewModel())
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79312274/first-time-content-not-getting-triggered-instantly[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия