1 /*
2  * Copyright 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.core.view;
18 
19 import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX;
20 
21 import android.content.Context;
22 import android.util.Log;
23 import android.view.MenuItem;
24 import android.view.SubMenu;
25 import android.view.View;
26 
27 import androidx.annotation.RestrictTo;
28 
29 import org.jspecify.annotations.NonNull;
30 import org.jspecify.annotations.Nullable;
31 
32 /**
33  * This class is a mediator for accomplishing a given task, for example sharing a file. It is
34  * responsible for creating a view that performs an action that accomplishes the task. This class
35  * also implements other functions such a performing a default action.
36  *
37  * <p>An ActionProvider can be
38  * optionally specified for a {@link android.view.MenuItem} and in such a case it will be
39  * responsible for
40  * creating the action view that appears in the {@link android.app.ActionBar} as a substitute for
41  * the menu item when the item is displayed as an action item. Also the provider is responsible for
42  * performing a default action if a menu item placed on the overflow menu of the ActionBar is
43  * selected and none of the menu item callbacks has handled the selection. For this case the
44  * provider can also optionally provide a sub-menu for accomplishing the task at hand.
45  *
46  * <p>There are two ways for using an action provider for creating and handling of action views:
47  *
48  * <ul><li> Setting the action provider on a {@link android.view.MenuItem} directly by
49  * calling {@link
50  * androidx.core.view.MenuItemCompat#setActionProvider(android.view.MenuItem, ActionProvider)}.
51  * </li>
52  *
53  * <li>Declaring the action provider in the menu XML resource. For example:
54  *
55  * <pre><code>
56  *   &lt;item android:id="@+id/my_menu_item"
57  *     android:title="@string/my_menu_item_title"
58  *     android:icon="@drawable/my_menu_item_icon"
59  *     android:showAsAction="ifRoom"
60  *     android:actionProviderClass="foo.bar.SomeActionProvider" /&gt;
61  * </code></pre>
62  * </li></ul></p>
63  *
64  * ### Creating a custom action provider
65  *
66  * <p>To create a custom action provider, extend ActionProvider and implement
67  * its callback methods as necessary. In particular, implement the following
68  * methods:</p>
69  *
70  * <dl>
71  * <dt>{@link #ActionProvider ActionProvider()} constructor</dt>
72  * <dd>This constructor is passed the application context. You should
73  * save the context in a member field to use in the other callback methods.</dd>
74  *
75  * <dt>{@link #onCreateActionView onCreateActionView(MenuItem)}</dt>
76  * <dd>The system calls this method when the action provider is created.
77  * You define the action provider's layout through the implementation of this
78  * method. Use the context acquired
79  * from the constructor to instantiate a {@link android.view.LayoutInflater} and
80  * inflate your action provider's layout from an XML resource, then hook up
81  * event listeners for the view's components. For example:
82  *
83  *<pre>
84  * public View onCreateActionView(MenuItem forItem) {
85  *     // Inflate the action provider to be shown on the action bar.
86  *     LayoutInflater layoutInflater = LayoutInflater.from(mContext);
87  *     View providerView =
88  *         layoutInflater.inflate(R.layout.my_action_provider, null);
89  *     ImageButton button =
90  *         (ImageButton) providerView.findViewById(R.id.button);
91  *     button.setOnClickListener(new View.OnClickListener() {
92  *         &#64;Override
93  *         public void onClick(View v) {
94  *             // Do something...
95  *         }
96  *     });
97  *     return providerView;
98  * }</pre>
99  * </dd>
100  *
101  * <dt>{@link #onPerformDefaultAction onPerformDefaultAction()}</dt>
102  * <dd><p>The system calls this method when the user selects a menu item from the action
103  * overflow. The action provider should perform a default action for the
104  * menu item. The system does not call this method if the menu item opens a submenu.</p>
105  *
106  * <p>If your action provider presents a submenu through the
107  * {@link #onPrepareSubMenu onPrepareSubMenu()} callback, the submenu
108  * appears even if the action provider is in the overflow menu.
109  * Thus, the system never calls {@link #onPerformDefaultAction
110  * onPerformDefaultAction()} if there is a submenu.</p>
111  *
112  * <p class="note"> <strong>Note:</strong> An activity or a fragment that
113  * implements <code>onOptionsItemSelected()</code> can override the action
114  * provider's default behavior (unless it uses a submenu) by handling the
115  * item-selected event and returning <code>true</code>. In this case, the
116  * system does not call
117  * {@link #onPerformDefaultAction onPerformDefaultAction()}.</p></dd>
118  * </dl>
119  *
120  *
121  * @see androidx.core.view.MenuItemCompat#setActionProvider(android.view.MenuItem, ActionProvider)
122  * @see androidx.core.view.MenuItemCompat#getActionProvider(android.view.MenuItem)
123  */
124 public abstract class ActionProvider {
125     private static final String TAG = "ActionProvider(support)";
126     private final Context mContext;
127 
128     private SubUiVisibilityListener mSubUiVisibilityListener;
129     private VisibilityListener mVisibilityListener;
130 
131     /**
132      * Creates a new instance.
133      *
134      * @param context Context for accessing resources.
135      */
ActionProvider(@onNull Context context)136     public ActionProvider(@NonNull Context context) {
137         mContext = context;
138     }
139 
140     /**
141      * Gets the context associated with this action provider.
142      */
getContext()143     public @NonNull Context getContext() {
144         return mContext;
145     }
146 
147     /**
148      * Factory method for creating new action views.
149      *
150      * @return A new action view.
151      */
onCreateActionView()152     public abstract @NonNull View onCreateActionView();
153 
154     /**
155      * Factory method called by the Android framework to create new action views.
156      * This method returns a new action view for the given MenuItem.
157      *
158      * <p>If your ActionProvider implementation overrides the deprecated no-argument overload
159      * {@link #onCreateActionView()}, overriding this method for devices running API 16 or later
160      * is recommended but optional. The default implementation calls {@link #onCreateActionView()}
161      * for compatibility with applications written for older platform versions.</p>
162      *
163      * @param forItem MenuItem to create the action view for
164      * @return the new action view
165      */
166     @SuppressWarnings("unused")
onCreateActionView(@onNull MenuItem forItem)167     public @NonNull View onCreateActionView(@NonNull MenuItem forItem) {
168         return onCreateActionView();
169     }
170 
171     /**
172      * The result of this method determines whether or not {@link #isVisible()} will be used
173      * by the {@link MenuItem} this ActionProvider is bound to help determine its visibility.
174      *
175      * @return true if this ActionProvider overrides the visibility of the MenuItem
176      *         it is bound to, false otherwise. The default implementation returns false.
177      * @see #isVisible()
178      */
overridesItemVisibility()179     public boolean overridesItemVisibility() {
180         return false;
181     }
182 
183     /**
184      * If {@link #overridesItemVisibility()} returns true, the return value of this method
185      * will help determine the visibility of the {@link MenuItem} this ActionProvider is bound to.
186      *
187      * <p>If the MenuItem's visibility is explicitly set to false by the application,
188      * the MenuItem will not be shown, even if this method returns true.</p>
189      *
190      * @return true if the MenuItem this ActionProvider is bound to is visible, false if
191      *         it is invisible. The default implementation returns true.
192      */
isVisible()193     public boolean isVisible() {
194         return true;
195     }
196 
197     /**
198      * If this ActionProvider is associated with an item in a menu,
199      * refresh the visibility of the item based on {@link #overridesItemVisibility()} and
200      * {@link #isVisible()}. If {@link #overridesItemVisibility()} returns false, this call
201      * will have no effect.
202      */
refreshVisibility()203     public void refreshVisibility() {
204         if (mVisibilityListener != null && overridesItemVisibility()) {
205             mVisibilityListener.onActionProviderVisibilityChanged(isVisible());
206         }
207     }
208 
209     /**
210      * Performs an optional default action.
211      *
212      * <p>For the case of an action provider placed in a menu
213      * item not shown as an action this method is invoked if previous callbacks for processing menu
214      * selection has handled the event.
215      *
216      * <p> A menu item selection is processed in the following order:
217      *
218      * <ul><li>Receiving a call to
219      * {@link android.view.MenuItem.OnMenuItemClickListener#onMenuItemClick
220      * MenuItem.OnMenuItemClickListener.onMenuItemClick}.</li>
221      *
222      * <li>Receiving a call to
223      * {@link android.app.Activity#onOptionsItemSelected(android.view.MenuItem)}
224      * FragmentActivity.onOptionsItemSelected(MenuItem)}
225      * </li>
226      *
227      * <li>Receiving a call to
228      * {@link androidx.fragment.app.Fragment#onOptionsItemSelected(android.view.MenuItem)}
229      * Fragment.onOptionsItemSelected(MenuItem)}</li>
230      *
231      * <li>Launching the {@link android.content.Intent} set via
232      * {@link android.view.MenuItem#setIntent(android.content.Intent)
233      * MenuItem.setIntent(android.content.Intent)}
234      * </li>
235      *
236      * <li>Invoking this method.</li></ul>
237      *
238      * <p>The default implementation does not perform any action and returns false.
239      */
onPerformDefaultAction()240     public boolean onPerformDefaultAction() {
241         return false;
242     }
243 
244     /**
245      * Determines if this ActionProvider has a submenu associated with it.
246      *
247      * <p>Associated submenus will be shown when an action view is not. This provider instance will
248      * receive a call to {@link #onPrepareSubMenu(SubMenu)} after the call to {@link
249      * #onPerformDefaultAction()} and before a submenu is displayed to the user.
250      *
251      * @return true if the item backed by this provider should have an associated submenu
252      */
hasSubMenu()253     public boolean hasSubMenu() {
254         return false;
255     }
256 
257     /**
258      * Called to prepare an associated submenu for the menu item backed by this ActionProvider.
259      *
260      * <p>if {@link #hasSubMenu()} returns true, this method will be called when the menu item is
261      * selected to prepare the submenu for presentation to the user. Apps may use this to create or
262      * alter submenu content right before display.
263      *
264      * @param subMenu Submenu that will be displayed
265      */
266     @SuppressWarnings("unused")
onPrepareSubMenu(@onNull SubMenu subMenu)267     public void onPrepareSubMenu(@NonNull SubMenu subMenu) {
268     }
269 
270     /**
271      * Notify the system that the visibility of an action view's sub-UI such as an anchored popup
272      * has changed. This will affect how other system visibility notifications occur.
273      *
274      */
275     @RestrictTo(LIBRARY_GROUP_PREFIX)
subUiVisibilityChanged(boolean isVisible)276     public void subUiVisibilityChanged(boolean isVisible) {
277         if (mSubUiVisibilityListener != null) {
278             mSubUiVisibilityListener.onSubUiVisibilityChanged(isVisible);
279         }
280     }
281 
282     /**
283      */
284     @RestrictTo(LIBRARY_GROUP_PREFIX)
setSubUiVisibilityListener(@ullable SubUiVisibilityListener listener)285     public void setSubUiVisibilityListener(@Nullable SubUiVisibilityListener listener) {
286         mSubUiVisibilityListener = listener;
287     }
288 
289     /**
290      * Set a listener to be notified when this ActionProvider's overridden visibility changes.
291      * This should only be used by MenuItem implementations.
292      *
293      * @param listener listener to set
294      */
setVisibilityListener(@ullable VisibilityListener listener)295     public void setVisibilityListener(@Nullable VisibilityListener listener) {
296         if (mVisibilityListener != null && listener != null) {
297             Log.w(TAG, "setVisibilityListener: Setting a new ActionProvider.VisibilityListener " +
298                     "when one is already set. Are you reusing this " + getClass().getSimpleName() +
299                     " instance while it is still in use somewhere else?");
300         }
301         mVisibilityListener = listener;
302     }
303 
304     /**
305      */
306     @RestrictTo(LIBRARY_GROUP_PREFIX)
reset()307     public void reset() {
308         mVisibilityListener = null;
309         mSubUiVisibilityListener = null;
310     }
311 
312     /**
313      */
314     @RestrictTo(LIBRARY_GROUP_PREFIX)
315     public interface SubUiVisibilityListener {
316 
onSubUiVisibilityChanged(boolean isVisible)317         void onSubUiVisibilityChanged(boolean isVisible);
318     }
319 
320     /**
321      * Listens to changes in visibility as reported by {@link ActionProvider#refreshVisibility()}.
322      *
323      * @see ActionProvider#overridesItemVisibility()
324      * @see ActionProvider#isVisible()
325      */
326     public interface VisibilityListener {
onActionProviderVisibilityChanged(boolean isVisible)327         void onActionProviderVisibilityChanged(boolean isVisible);
328     }
329 }
330