getSupportActionBar从片段ActionBarCompat内 [英] getSupportActionBar from inside of Fragment ActionBarCompat
问题描述
我开始了使用 AppCompat / ActionBarCompat
在 V7
支持库一个新项目。我试图找出如何使用 getSupportActionBar
从片段中。我承载片段活动来延长 ActionBarActivity
,但我没有看到碎片类似的辅助类。
I'm starting a new project that uses the AppCompat/ActionBarCompat
in v7
support library. I'm trying to figure out how to use the getSupportActionBar
from within a fragment. My activity that hosts the fragment extends ActionBarActivity
, but I don't see a similar support class for Fragments.
这是我的片段中
public class CrimeFragment extends Fragment {
//...
getActivity().getSupportActionBar().setSubtitle(R.string.subtitle); // getSupportActionBar is not defined in the v4 version of Fragment
//...
}
在谷歌页面使用它(<一href="http://android-developers.blogspot.in/2013/08/actionbarcompat-and-io-2013-app-source.html">http://android-developers.blogspot.in/2013/08/actionbarcompat-and-io-2013-app-source.html)说,不应该有任何的变化为 V4
片段。我需要投我所有的 getActivity()
调用一个 ActionBarActivity
?这似乎是设计不良。
The google page for using it (http://android-developers.blogspot.in/2013/08/actionbarcompat-and-io-2013-app-source.html) says there should be no changes for the v4
fragment. Do I need to cast all my getActivity()
calls to an ActionBarActivity
? That seems like poor design.
推荐答案
Fragment.onActivityCreated(...)后,你必须通过getActivity访问的有效活动()。你需要将其转换为一个ActionBarActivity然后进行调用getSupportActionBar()。
After Fragment.onActivityCreated(...) you'll have a valid activity accessible through getActivity(). You'll need to cast it to an ActionBarActivity then make the call to getSupportActionBar().
((ActionBarActivity)getActivity()).getSupportActionBar().setSubtitle(R.string.subtitle);
您需要做的转换。这不是设计差,则是向后兼容的。
You do need the cast. It's not poor design it's backwards compatibility.
这篇关于getSupportActionBar从片段ActionBarCompat内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!