Android: Update Badge count of Bottom Navigation View in activity from Fragment

Viewed 271

I've implemented bottom navigation view with badge for notification count in my application. i set the count via a server call inside my DashBoardActivity and i've a notification fragment where i display all the notifications. now issue is that when i click on any of the notifications i'm not able to update the count in my activity. i tried updating the count by using interface but it doesn't seem to work.

listener.onNotificationClick(count)

i also tried creating a variable and updating it from fragment but no effect

(activity as DashboardActivity).notificationsCount = count

DashBoardActivity.kt where i'm showing the badge

class DashboardActivity : BaseActivity<>() {

private val viewModel: DashBoardViewModel by viewModels()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_dashboard)

    viewModel.fetchNotifications()

    observeNotifications()
}

private fun observeNotifications() {

    viewModel.notificationLiveData.observe(this, Observer {
        when (it) {
            is NotificationResponse -> {
                showBadge(it.recordsTotal!!)
            }
            else -> {
                Log.e(it.message)
            }
        }
    })
}

private fun showBadge(count: Int) {
    val navBar: BottomNavigationView = mViewBinding.bottomNavigationView

    val badge = navBar.getOrCreateBadge(R.id.nav_notifications_fragment)

    badge.backgroundColor = getColor(R.color.colorRed)
    badge.maxCharacterCount = 3
    badge.isVisible = count > 0
    badge.number = count
}

NotifcationFragment where i'm listening the clicks

class NotificationsFragment : BaseFragment<>(),
BaseAdapter.BaseInterface {

override fun onNotificationClicked(dataType: Any?, view: View?, position: Int) {
    Update the counter
}

am i doing it wrong or what should i do to resolve this issue

0 Answers
Related