In writing the project is faced with this situation. I have several activations and in each of them there is a toolbar of the same type. I do not want to prescribe the same strings in each of them, and therefore I created the abstract class BaseActivity. The onCreate method in it works perfectly, but for some reason, the onCreateOptionsMenu method does not want to show me my 3 right icons in each of the activations inherited from BaseActivity. This method is just null! Is there another way to create a menu, or does something need to be added so that the icons show up after all? The menu itself was created in the classical way - through a drawable with writing item. Abstract class code:

import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; public abstract class BaseActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); } } 
  • one
    Attach abstract class code - Vennic
  • Added by top edit - Anton Pankratov
  • one
    At the time of the call to findViewById(R.id.toolbar) layout has not yet been set (there was no call to setContentView(...) - therefore the toolbar was not found and not installed. - woesss
  • one
    @woesss, I apologize, at the time of writing the answer, your comment was not :) - Vennic

1 answer 1

In the onCreate () method you do not have the setContentView () method, you do not get your View from the layout, and therefore findViewById (R.Id.toolbar) cannot find your toolbar

Do as here, only instead of R.layout.acyivity_fragment set your layout

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fragment); } 

Ps do not forget that for each activit you need to set your layout, I think it is easier to leave only onCreateOptionsMenu () in the abstract class, and onCreate () to register in the Activity classes themselves, because the method can vary greatly for each activit.