I have an envelope icon in ActionBar which is the message indicator ... I want to make sure that the number of unread messages is displayed right next to the envelope icon. I installed the envelope icon, but I don’t know how to install some textview next to it in which you can set the corresponding message number ... or maybe there is some ready-made solution for how to do it correctly ...

That's how I set the menu in the code

@Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } 

and that's how I wrote an XML file

 <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity"> <item android:id="@+id/main" android:icon="@drawable/message" android:title="Menu" app:showAsAction="ifRoom|withText" /> </menu> 

and this is how it looks

enter image description here

  • The only possible option that I see in this case is to prepare a lot of icons that will have the right number next to the envelope, and then return the desired icon with a switch. I'm afraid to put a TextView there will not work - Werder

1 answer 1

I advise you to use a custom toolbar and in it add the component heir to the button with the text field where you need it. With this approach, you can work with the toolbar as with the usual View .

tollbar.xml

 <?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar_actionbar" android:layout_width="match_parent" android:layout_height="?android:actionBarSize" android:background="@color/colorPrimary" app:theme="@style/ShoppingListTheme"> <!-- тут размести элемент кнопки --> </android.support.v7.widget.Toolbar> 

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <include layout="@layout/toolbar"/> <!-- тут, как обычно, размести внутренние элементы активити --> </android.support.design.widget.CoordinatorLayout> 

MainActivity.java

 public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private Toolbar mActionBarToolbar; private YourCustomButton mYourCustomButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar); setSupportActionBar(mActionBarToolbar); mYourCustomButton = (YourCustomButton) mActionBarToolbar.findViewById(R.id.yourCustomButtonId); } } 

Next, push the number of messages to the mYourCustomButton button and you mYourCustomButton done.

The code of the button itself is not needed?