I have a toolbar in my fragment that I need to set the activity's action bar, however, I get null whenever I call getSupportActionBar() method, anyone can help?
My activity:
public class MainActivity1 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
Fragment fragment = new HomeFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.main, fragment).commit();
}
}
Style.xml the activity is using the AppTheme.NoActionBar
theme
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
Fragment code:
public class HomeFragment extends Fragment {
DrawerLayout drawer;
Toolbar toolbar;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
setupToolbar();
return view;
}
public void setupToolbar() {
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
}
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); this line in the fragment will always return null.