android-无法在扩展FragmentActivity的类中解析方法getActivity()
作者:互联网
我在一个类中扩展了Fragment Activity,在该类中,我还需要一个自定义工具栏.因此,我添加了获取工具栏的代码,但setSupportActionBar(toolbar)无法正常工作.然后,我添加了AppCompatActivity.getActivity()进行强制转换,但效果不佳.
这是代码-
public class main_fragment extends FragmentActivity implements FragmentDrawer.FragmentDrawerListener {
private Toolbar toolbar;
private FragmentDrawer drawerFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_fragment);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
drawerFragment.setDrawerListener(this);
}
解决方法:
AppCompatActivity扩展了FragmentActivity.您必须更改的第一件事是
extends FragmentActivity
与
extends AppCompatActivity
getActivity()是Fragment的一种方法. Activity没有该方法,因此您无需调用它即可使用setSupportActionBar和getSupportActionBar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
标签:android-toolbar,fragment,android-fragmentactivity,android 来源: https://codeday.me/bug/20191119/2036839.html