Reputation: 1
I am new to Android Development and currently learning Jetpack Compose. Recently, I started a simple Notes application using Room Database with MVVM Architecture. I am facing an issue of Note color disappearance while switching between different orientations (Note Title and Note Content remains intact). I am using ViewModel to remember the states.
If I start the application in Landscape orientation then Colors appear normally, but while switching the orientation Colors disappear, and switching back to landscape orientation make them visible again.
Here is my ViewModel Class:
class NoteViewModel(application: Application): AndroidViewModel(application) {
val getAllNotes: LiveData<List<Note>>
private val repository: NoteRepository
init{
val noteDao = NoteDatabase.getDatabase(application).noteDao()
repository = NoteRepository(noteDao)
getAllNotes = repository.getAllNotes()
}
fun addNote(note:Note){
viewModelScope.launch(Dispatchers.IO){
repository.addNote(note)
}
}
}
Here is my Entity Class:
@Entity(tableName = "note_table")
data class Note(
@PrimaryKey(autoGenerate = true)
val id:Int,
@ColumnInfo(name = "NoteTitle")
val title:String,
@ColumnInfo(name = "NoteText")
val text:String,
@ColumnInfo(name = "NoteColor")
val color:Int,
@ColumnInfo(name = "IsTodo")
val isTodo:Boolean
){
companion object{
val noteColors = listOf(
Color.White,
Yellow300,
Green300,
Red300,
Blue300,
Magenta300,
)
}
}
this is my Note Card Composable
@Composable
fun NoteCard(
modifier:Modifier = Modifier,
noteTitle:String,
noteContent:String,
getNoteColorFromIndex:Int,
currentNoteIndex:Int,
) {
val noteColor by remember{mutableStateOf(noteColors[getNoteColorFromIndex])} //this noteColors is from Entity's Class Companion Object
var noteState by remember{ mutableStateOf(NoteState.Collapsed)}
val transition = updateTransition(targetState = noteState,label = "Expanded State")
val arrowRotate by transition.animateFloat(
label = "Arrow Rotation"
) { state ->
when(state){
NoteState.Collapsed -> 0f
NoteState.Expanded -> 180f
}
}
NoteCardView(
noteTitle,
noteContent,
noteColor,
currentNoteIndex,
noteState,
arrowRotate,
modifier
){
noteState = when(noteState){
NoteState.Collapsed -> NoteState.Expanded
NoteState.Expanded -> NoteState.Collapsed
}
}
}
And calling of above Composable using ViewModel
NoteCard(
noteTitle = ListOfNotes[index].title,
noteContent = ListOfNotes[index].text,
getNoteColorFromIndex = ListOfNotes[index].color,
currentNoteIndex = index
)
Upvotes: 0
Views: 143
Reputation: 1
Just figured out if I add a Toast message in NoteCard then it works fine ¯\(ツ)/¯
but it is not a proper solution
Upvotes: 0