Helper Helper - 2 months ago 11
Android Question

Menu disappeared after extending the Activity with BaseActivity

I have following code in all Activity files. I will use same menu for all activities. Here is the code.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}


Instead of duplicating this code in all activities, I created a BaseActivity with following code.

public class BaseActivity extends Activity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}


Now all the Activities are extending BaseActivity like below.

public class AddItemActivity extends BaseActivity {

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


Problem



Menu is disappeared due to above code. Am I doing something wrong?

Answer

Change below line:

public class BaseActivity extends Activity

to below

public class BaseActivity extends AppCompatActivity

I created a simple project likely what you need. Please checkout it here: https://github.com/briannl/OptionMenuExample