Skeellz
Skeellz

Reputation: 71

How do I align an inflated custom view with the rest of the menu items in Toolbar

I don't really know how to put this but all I want is a toolbar (action bar) like the WhatsApp style below.

The style I want

The style I have managed to develop so far

Meanwhile, I used the Android toolbar and inflated a custom view (which holds the cart button) and added it using the setCustomView() method. I tried tweaking the textSize attribute of the TextView but even the most reasonable size doesn't align the TextView with the rest of the Toolbar menu items. Any help on how to do this? Or is there a different approach?

Upvotes: 1

Views: 297

Answers (1)

Ruan_Lopes
Ruan_Lopes

Reputation: 1399

If I understood you correctly I suggest a different approach, you can set toolbar as a SupportActionBar and add your custom icons as you would do in a normal actionBar

  1. Set your toolbar as SupportActionBar

ex.

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
  1. Create a menu file as you would do to a normal actionBar

ex.

 <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action1"
        android:orderInCategory="100"
        android:title="CUSTOM TITTLE"
        android:icon="@drawable/custom_icon1"
        app:showAsAction="always" />

    <item
        android:id="@+id/action2"
        android:orderInCategory="100"
         android:title="CUSTOM TITTLE"
        android:icon="@drawable/custom_icon2"
        app:showAsAction="ifRoom"  />

   </menu>
  1. Finally use onCreateOptionsMenu and onOptionsItemSelected to finish to setup.

ex.

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.custom_menu, menu);

    .....

    return true;
}

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    switch (item.getItemId()) {
        case R.id.action_custom_view:

            .....Your code.....

            break;
        case android.R.id.action_custom_view2:

             .....Your code.....

            break;
    }

    return false;

}

Upvotes: 1

Related Questions