I want to show Back Arrow in Fragments ToolBar. Im trying to write this code: ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
but AS writes: method invokation .. may produce "java.lang.NullPointerException". What about getSupportActionBar(), AS writes cannot resolve method. Whats wrong? Here is my code:
public class AddFilterFrag extends android.app.Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.add_filter_layout, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
//something to do
return true;
}
return super.onOptionsItemSelected(item);
}
This is just a warning you can safely ignore.
Background:
The Android sdk has Annotations to help developers avoid common mistakes. One of those annotations is @Nullable
. The method getSupportActionBar()
is annotated as such, as it is possible that null
is returned from that method. One case might be, that the developer used the theme Theme.AppCompat.Light.NoActionBar
thus disabling the ActionBar.
If you have an ActionBar or a Toolbar in your layout (and set it properly) that method will never return null
. You can ignore the warning like this:
//noinspection ConstantConditions
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Or if you want to be absolutely safe:
ActionBar ab = ((AppCompatActivity) getActivity()).getSupportActionBar();
if(ab != null){
ab.setDisplayHomeAsUpEnabled(true);
}
Alternatively in Kotlin:
(activity as? AppCompatActivity)?.supportActionBar?.setDisplayHomeAsUpEnabled(true)
Frist add method to your activity that call fragment.
public void changeToolbar(){ //Do your job }
call it in fragment
((YourActivity)getActivity).changeToolbar();
while using navigation graphs use navController to do that
On the activity thats holding the host fragment do this
lateinit var navController : NavController
In oncreateView
navController = this.findNavController(R.id.nav_host_fragment)
NavigationUI.setupActionBarWithNavController(this, navController)
override onSupportNavigateUp
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp()
}
that handles the up arrow by itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With