Custom icon in Android toolbar

后端 未结 4 1256
死守一世寂寞
死守一世寂寞 2020-12-30 05:30

I\'m trying to use define a custom icon in the support Toolbar but the only icon shown is a left arrow... I tried to set it in the layout and programmatically but the result

相关标签:
4条回答
  • 2020-12-30 06:18
    ActionBar.setHomeAsUpIndicator(...);
    

    This one works for me.

    0 讨论(0)
  • 2020-12-30 06:25

    In case you want to change menu icon. (maybe somebody will need it)

    1. In your activity

      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
          MenuInflater inflater = getMenuInflater();
          inflater.inflate(R.menu.menu_info, menu);
          return true;
      }
      
    2. in your menu folder in res. (menu_info.xml)

      <?xml version="1.0" encoding="utf-8"?>
      <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
          <item
              android:id="@+id/menu_info_action"
              android:icon="@drawable/ic_info_icon"
              android:title="@string/information"
              app:showAsAction="ifRoom"/>
      </menu>
      
    0 讨论(0)
  • 2020-12-30 06:26

    Just tried it myself and the issue seems to be that you have to call setNavigationIcon after setSupportActionBar(toolbar). Otherwise it'll only show the arrow as you've described.
    So to fix this issue just change the code like this:

    //...
    Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(toolbar);
    toolbar.setNavigationIcon(R.drawable.ic_launcher);
    toolbar.setTitle("");
    

    Note: Same goes for setting the title, contentDescription etc. I don't know if this a bug or if it is intended, but it's definitely kinda strange.

    0 讨论(0)
  • 2020-12-30 06:29

    The current most efficient way to achieve this:

    first display the left hand side icon correctly, call this function in onCreateView or onCreate:

    protected void enableDisplayHomeAsHome(boolean active) {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(active); // switch on the left hand icon
            actionBar.setHomeAsUpIndicator(R.drawable.ic_action_home); // replace with your custom icon
        }
    }
    

    Now you can intercept this button press in your activity:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: {  //index returned when home button pressed
                homeButtonPressed();
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }
    
    0 讨论(0)
提交回复
热议问题