Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

android - How to get Toolbar from fragment?

I have ActionBarActivity with NavigationDrawer and use support_v7 Toolbar as ActionBar. In one of my fragments toolbar has custom view. In other fragments Toolbar should show title.

How get Toolbar instance for customizing from fragments? I can get ActionBar with getActivity().getActionBar(), but if I call setTitle() for this instance ActionBar it do nothing.

UPD:

In my case

((ActionBarActivity) getActivity()).getSupportActionBar().setTitle();

(as MrEngineer13 said) don't work at first fragment creation because I call it from onHiddenChanged(). Now I add more one to onCreateView() and it works fine.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to cast your activity from getActivity() to AppCompatActivity first. Here's an example:

((AppCompatActivity) getActivity()).getSupportActionBar().setTitle();

The reason you have to cast it is because getActivity() returns a FragmentActivity and you need an AppCompatActivity

In Kotlin:

(activity as AppCompatActivity).supportActionBar?.title = "My Title"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...