11package org .xedox .utils ;
22
3+ import android .util .Log ;
4+ import android .view .Menu ;
5+ import android .view .MenuItem ;
36import android .view .View ;
47import androidx .activity .OnBackPressedCallback ;
58import androidx .appcompat .app .AppCompatActivity ;
811import androidx .core .view .WindowCompat ;
912import androidx .core .view .WindowInsetsCompat ;
1013import com .google .android .material .snackbar .Snackbar ;
14+ import java .lang .reflect .Method ;
15+ import java .util .HashMap ;
16+ import java .util .Map ;
1117
1218public class BaseActivity extends AppCompatActivity {
19+ protected final Map <Integer , Boolean > menuItemsVisibility = new HashMap <>();
20+ protected final Map <Integer , Boolean > menuItemsEnabled = new HashMap <>();
1321
1422 @ Override
1523 protected void onStart () {
@@ -28,6 +36,16 @@ public void handleOnBackPressed() {
2836 applyWindowInsets (findViewById (android .R .id .content ));
2937 }
3038
39+ public void updateItemVisibility (int itemId , boolean visible ) {
40+ menuItemsVisibility .put (itemId , visible );
41+ invalidateOptionsMenu ();
42+ }
43+
44+ public void updateItemEnabled (int itemId , boolean enabled ) {
45+ menuItemsEnabled .put (itemId , enabled );
46+ invalidateOptionsMenu ();
47+ }
48+
3149 public void applyWindowInsets (View view ) {
3250 ViewCompat .setOnApplyWindowInsetsListener (
3351 view ,
@@ -45,6 +63,38 @@ public void applyWindowInsets(View view) {
4563 });
4664 }
4765
66+ public boolean onCreateOptionsMenu (int menuId , Menu menu ) {
67+ getMenuInflater ().inflate (menuId , menu );
68+ for (Map .Entry <Integer , Boolean > entry : menuItemsVisibility .entrySet ()) {
69+ MenuItem item = menu .findItem (entry .getKey ());
70+ if (item != null ) {
71+ item .setVisible (entry .getValue ());
72+ }
73+ }
74+ for (Map .Entry <Integer , Boolean > entry : menuItemsEnabled .entrySet ()) {
75+ MenuItem item = menu .findItem (entry .getKey ());
76+ if (item != null ) {
77+ item .setEnabled (entry .getValue ());
78+ }
79+ }
80+ return true ;
81+ }
82+
83+ @ Override
84+ public boolean onPrepareOptionsMenu (Menu menu ) {
85+ if (menu != null && menu .getClass ().getSimpleName ().equals ("MenuBuilder" )) {
86+ try {
87+ Method m =
88+ menu .getClass ().getDeclaredMethod ("setOptionalIconsVisible" , Boolean .TYPE );
89+ m .setAccessible (true );
90+ m .invoke (menu , true );
91+ } catch (Exception e ) {
92+ Log .e ("OverflowMenu" , "Error forcing menu icons to show" , e );
93+ }
94+ }
95+ return super .onPrepareOptionsMenu (menu );
96+ }
97+
4898 public void showSnackbar (int text , int type ) {
4999 Snackbar .make (findViewById (android .R .id .content ), text , type )
50100 .setAction (R .string .ok , null )
0 commit comments