Alex Rodionow
Alex Rodionow

Reputation: 257

How to set and update the title in the toolbar by clicking menu items in the Fragment?

I need to set the name of chosen category, below is the category object code and methods I call by clicking. Grateful for helping.

categoryItem object:

@Entity(tableName = "category_table")
@Parcelize
data class CategoryItem(
    val categoryName: String,
    val categoryNumber: Int,
    val categoryShown: Boolean = false,
    @PrimaryKey(autoGenerate = true) var id: Int = 0
) : Parcelable {
}

In Menu:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_cat1 -> {
                viewModel.onChooseCategoryClick(1)
                true
            }
            R.id.action_cat2 -> {
                viewModel.onChooseCategoryClick(2)
                true
            }

onChooseCategoryClick() in ViewModel:

fun onChooseCategoryClick(chosenCategory: Int) = viewModelScope.launch {
    preferencesManager.updateCategoryChosen(chosenCategory)
    // what to type here
}

in preferencesManager:

suspend fun updateCategoryChosen(categoryChosen: Int) {
    dataStore.edit { preferences ->
        preferences[PreferencesKeys.CATEGORY_CHOSEN] = categoryChosen
    }
}

Upvotes: 0

Views: 112

Answers (1)

Mohammad Zarei
Mohammad Zarei

Reputation: 1802

The choosenCategory value is the same as the id of one of the items on your menu items. So you can find it using when:

when(choosenCategory){
    R.id.action_cat1->
    R.id.action_cat2->
}

Upvotes: 2

Related Questions