0

I would like the user to be able to tap the title in the toolbar and perform an action when it does:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
...
}
1

1 Answer 1

2

If you use the Toolbar as replacement for the ActionBar, the title is not clickable. You can setDisplayHomeAsUpEnabled which will display the back arrow and handle the click in onOptionsItemSelected

  Toolbar tb = (Toolbar) findViewById(R.id.my_awesome_toolbar);
   setSupportActionBar(tb);
   getSupportActionBar().setTitle("test");
   getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Click

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}

Alternatively, since the ToolBar is a ViewGroup, you could host a TextView

<android.support.v7.widget.Toolbar
    android:id="@+id/my_awesome_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    </android.support.v7.widget.Toolbar>

and programmatically you can register a View.OnClickListener. E.g.

Toolbar tb = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(tb);
tb.findViewById(R.id.title).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        finish();
    }
});
getSupportActionBar().setTitle(null);
4
  • Can I replace the icon?
    – user3109249
    Commented Oct 22, 2015 at 18:21
  • it should be possible with toolBar.setNavigationIcon
    – Blackbelt
    Commented Oct 22, 2015 at 18:23
  • Can I change the size of the new icon? whether in the MainActivity.java or in the layout file.
    – user3109249
    Commented Oct 22, 2015 at 18:32
  • 5
    Could you make a small effort and just try?
    – Blackbelt
    Commented Oct 22, 2015 at 18:35