Update a counter within the NavigationView (side menu) on Android
I have a NavigationView
with an element where there is a counter to its right, to indicate how many elements there are to see.
In customize NavigationView menu layout I have followed the steps to add a counter more or less like the following image
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/my_counter"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="0"
android:textAppearance="@style/TextAppearance.AppCompat.Body2" />
To modify its content I use setText
TextView myCounter = (TextView) this.findViewById(R.id.my_counter);
if (myCounter != null) {
myCounter.setText("99+");
}
If I put it inside a onClick
event of a button, the value from 0
to 99+
But I can't get to modify it when the app starts, I've tested it on onCreate() y onStart()
I've searched for SO and some solutions is to use a runnable
, but I don't think it's the most appropriate thing to expect the menu to be fully loaded to modify the counter value.
1 answers
To change the counter value dynamically when the activity
is launched, it must be done in the event where menu items are prepared, onPrepareOptionsMenu
@SuppressLint("SetTextI18n")
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
TextView myCounter = (TextView) this.findViewById(R.id.my_counter);
if (myCounter != null) {
myCounter.setText("99+");
}
return super.onPrepareOptionsMenu(menu);
}