Remove ActionBar subtitle / Reset ActionBar text

2019-04-22 05:05发布

问题:

I'm currently setting the ActionBar subtitle on certain pages, but on some pages i don't want to have a subtitle.

I can simply set the text of the subtitle to nothing, but this just removes the text. It still occupies the subtitle space and thus pushes the title up. It can be hard to explain, so i illustrated with a picture:

1) This show the ActionBar with no subtitle set, which is how i want to be able to set it.

2 This shows the ActionBar with a subtitle set, which is how i want to show it on some pages.

3) And finally, this is how the ActionBar looks after i set a subtitle and try to remove it. As you can see, the title has been pushed up and the subtitle is not gone, it's just not showing anything.

I hope someone can help me out with this, i've tried googling the problem, i've digged through the official android website to find a getActionBar().ResetSubtitle() or similar, but so far i've come up empty handed.

回答1:

Call ActionBar.setSubtitle(null), this will change the visibility of the subtitle TextView to View.GONE.

Source

ActionBarView.setSubtitle



回答2:

Assuming you're using a Toolbar as your activity's ActionBar, you need to manually request the Toolbar layout its children. Although in theory Toolbar#requestLayout() would work, it only worked for me on its parent (CollapsingToolbarLayout). I suspect that wouldn't be required if that class wasn't its parent.

You might also investigate View#forceLayout() if layout still doesn't occur. For some reason, the automatic layout behaviour would stop in some situations, requiring layout to be requested manually. It can't do much harm to request it again.