how to reference ActionBar title View on Lollipop

2019-01-26 17:14发布

I have an Activity which extends the AppCompatActivity and uses the support ActionBar. Compile SDK version is 23, test devices SDK are 21-22. I need to get the ActionBar's title TextView, however, the most known way of doing this

int resId = getResources().getIdentifier("action_bar_title", "id", "android");
return (TextView) findViewById(resId);

doesn't work starting with API 21. Is there a way to reference the title TextView on Lollipop?

2条回答
一夜七次
2楼-- · 2019-01-26 17:28

With AppCompatActivity, You can retrieve the TextView that you want indirectly, because it seems that this TextView has no id, like this:

Toolbar toolbar = (Toolbar) findViewById(R.id.action_bar);
TextView textView = (TextView) toolbar.getChildAt(0);

I used the Hierarchy Viewer tool to get the view tree. (Tool that you can find into Android Device Monitor under Hierarchy View perspective)

Action bar view tree

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-26 17:35

Just some alternatives - you might consider defining your own custom textview to add to the toolbar if you wish to customize it - Adding custom view to a toolbar

Or extending Toolbar - findViewById returns null for action_bar_title

查看更多
登录 后发表回答