Home | History | Annotate | Download | only in ui
      1 page.title=Input Events
      2 parent.title=User Interface
      3 parent.link=index.html
      4 @jd:body
      5 
      6 <div id="qv-wrapper">
      7 <div id="qv">
      8   <h2>In this document</h2>
      9   <ol>
     10     <li><a href="#EventListeners">Event Listeners</a></li>
     11     <li><a href="#EventHandlers">Event Handlers</a></li>
     12     <li><a href="#TouchMode">Touch Mode</a></li>
     13     <li><a href="#HandlingFocus">Handling Focus</a></li>
     14   </ol>
     15 
     16   <h2>Related tutorials</h2>
     17   <ol>
     18     <li><a href="{@docRoot}resources/tutorials/views/hello-formstuff.html">Form Stuff</a></li>
     19   </ol>
     20 </div>
     21 </div>
     22 
     23 <p>On Android, there's more than one way to intercept the events from a user's interaction with your application.
     24 When considering events within your user interface, the approach is to capture the events from
     25 the specific View object that the user interacts with. The View class provides the means to do so.</p>
     26 
     27 <p>Within the various View classes that you'll use to compose your layout, you may notice several public callback 
     28 methods that look useful for UI events. These methods are called by the Android framework when the 
     29 respective action occurs on that object. For instance, when a View (such as a Button) is touched,
     30 the <code>onTouchEvent()</code> method is called on that object. However, in order to intercept this, you must extend
     31 the class and override the method. However, extending every View object
     32 in order to handle such an event would not be practical. This is why the View class also contains
     33 a collection of nested interfaces with callbacks that you can much more easily define. These interfaces,
     34 called <a href="#EventListeners">event listeners</a>, are your ticket to capturing the user interaction with your UI.</p>
     35 
     36 <p>While you will more commonly use the event listeners to listen for user interaction, there may
     37 come a time when you do want to extend a View class, in order to build a custom component. 
     38 Perhaps you want to extend the {@link android.widget.Button}
     39 class to make something more fancy. In this case, you'll be able to define the default event behaviors for your
     40 class using the class <a href="#EventHandlers">event handlers</a>.</p>
     41 
     42 
     43 <h2 id="EventListeners">Event Listeners</h2>
     44 
     45 <p>An event listener is an interface in the {@link android.view.View} class that contains a single 
     46 callback method. These methods will be called by the Android framework when the View to which the listener has
     47 been registered is triggered by user interaction with the item in the UI.</p>
     48 
     49 <p>Included in the event listener interfaces are the following callback methods:</p>
     50 
     51 <dl>
     52   <dt><code>onClick()</code></dt>
     53     <dd>From {@link android.view.View.OnClickListener}. 
     54     This is called when the user either touches the item 
     55     (when in touch mode), or focuses upon the item with the navigation-keys or trackball and
     56     presses the suitable "enter" key or presses down on the trackball.</dd>
     57   <dt><code>onLongClick()</code></dt>
     58     <dd>From {@link android.view.View.OnLongClickListener}. 
     59     This is called when the user either touches and holds the item (when in touch mode), or 
     60     focuses upon the item with the navigation-keys or trackball and
     61     presses and holds the suitable "enter" key or presses and holds down on the trackball (for one second).</dd>
     62   <dt><code>onFocusChange()</code></dt>
     63     <dd>From {@link android.view.View.OnFocusChangeListener}. 
     64     This is called when the user navigates onto or away from the item, using the navigation-keys or trackball.</dd>
     65   <dt><code>onKey()</code></dt>
     66     <dd>From {@link android.view.View.OnKeyListener}. 
     67     This is called when the user is focused on the item and presses or releases a hardware key on the device.</dd>
     68   <dt><code>onTouch()</code></dt>
     69     <dd>From {@link android.view.View.OnTouchListener}. 
     70     This is called when the user performs an action qualified as a touch event, including a press, a release,
     71     or any movement gesture on the screen (within the bounds of the item).</dd>
     72   <dt><code>onCreateContextMenu()</code></dt>
     73     <dd>From {@link android.view.View.OnCreateContextMenuListener}. 
     74     This is called when a Context Menu is being built (as the result of a sustained "long click"). See the discussion
     75     on context menus in the <a href="{@docRoot}guide/topics/ui/menus.html#context-menu">Menus</a>
     76     developer guide.</dd>
     77 </dl>
     78 
     79 <p>These methods are the sole inhabitants of their respective interface. To define one of these methods
     80 and handle your events, implement the nested interface in your Activity or define it as an anonymous class.
     81 Then, pass an instance of your implementation
     82 to the respective <code>View.set...Listener()</code> method. (E.g., call 
     83 <code>{@link android.view.View#setOnClickListener(View.OnClickListener) setOnClickListener()}</code> 
     84 and pass it your implementation of the {@link android.view.View.OnClickListener OnClickListener}.)</p>
     85 
     86 <p>The example below shows how to register an on-click listener for a Button. </p>
     87 
     88 <pre>
     89 // Create an anonymous implementation of OnClickListener
     90 private OnClickListener mCorkyListener = new OnClickListener() {
     91     public void onClick(View v) {
     92       // do something when the button is clicked
     93     }
     94 };
     95 
     96 protected void onCreate(Bundle savedValues) {
     97     ...
     98     // Capture our button from layout
     99     Button button = (Button)findViewById(R.id.corky);
    100     // Register the onClick listener with the implementation above
    101     button.setOnClickListener(mCorkyListener);
    102     ...
    103 }
    104 </pre>
    105 
    106 <p>You may also find it more convenient to implement OnClickListener as a part of your Activity.
    107 This will avoid the extra class load and object allocation. For example:</p>
    108 <pre>
    109 public class ExampleActivity extends Activity implements OnClickListener {
    110     protected void onCreate(Bundle savedValues) {
    111         ...
    112         Button button = (Button)findViewById(R.id.corky);
    113         button.setOnClickListener(this);
    114     }
    115 
    116     // Implement the OnClickListener callback
    117     public void onClick(View v) {
    118       // do something when the button is clicked
    119     }
    120     ...
    121 }
    122 </pre>
    123 
    124 <p>Notice that the <code>onClick()</code> callback in the above example has
    125 no return value, but some other event listener methods must return a boolean. The reason
    126 depends on the event. For the few that do, here's why:</p>
    127 <ul>
    128   <li><code>{@link android.view.View.OnLongClickListener#onLongClick(View) onLongClick()}</code> - 
    129     This returns a boolean to indicate whether you have consumed the event and it should not be carried further. 
    130     That is, return <em>true</em> to indicate that you have handled the event and it should stop here; 
    131     return <em>false</em> if you have not handled it and/or the event should continue to any other
    132     on-click listeners.</li>
    133   <li><code>{@link android.view.View.OnKeyListener#onKey(View,int,KeyEvent) onKey()}</code> - 
    134     This returns a boolean to indicate whether you have consumed the event and it should not be carried further.
    135     That is, return <em>true</em> to indicate that you have handled the event and it should stop here; 
    136     return <em>false</em> if you have not handled it and/or the event should continue to any other
    137     on-key listeners.</li>
    138   <li><code>{@link android.view.View.OnTouchListener#onTouch(View,MotionEvent) onTouch()}</code> - 
    139     This returns a boolean to indicate whether your listener consumes this event. The important thing is that
    140     this event can have multiple actions that follow each other. So, if you return <em>false</em> when the
    141     down action event is received, you indicate that you have not consumed the event and are also
    142     not interested in subsequent actions from this event. Thus, you will not be called for any other actions
    143     within the event, such as a finger gesture, or the eventual up action event.</li>
    144 </ul>
    145 
    146 <p>Remember that hardware key events are always delivered to the View currently in focus. They are dispatched starting from the top
    147 of the View hierarchy, and then down, until they reach the appropriate destination. If your View (or a child of your View)
    148 currently has focus, then you can see the event travel through the <code>{@link android.view.View#dispatchKeyEvent(KeyEvent)
    149 dispatchKeyEvent()}</code> method. As an alternative to capturing key events through your View, you can also receive 
    150 all of the events inside your Activity with <code>{@link android.app.Activity#onKeyDown(int,KeyEvent) onKeyDown()}</code>
    151 and <code>{@link android.app.Activity#onKeyUp(int,KeyEvent) onKeyUp()}</code>.</p>
    152 
    153 <p>Also, when thinking about text input for your application, remember that many devices only have software input
    154 methods. Such methods are not required to be key-based; some may use voice input, handwriting, and so on. Even if
    155 an input method presents a keyboard-like interface, it will generally <strong>not</strong> trigger the
    156 <code>{@link android.app.Activity#onKeyDown(int,KeyEvent) onKeyDown()}</code> family of events. You should never
    157 build a UI that requires specific key presses to be controlled unless you want to limit your application to devices
    158 with a hardware keyboard. In particular, do not rely on these methods to validate input when the user presses the
    159 return key; instead, use actions like {@link android.view.inputmethod.EditorInfo#IME_ACTION_DONE} to signal the
    160 input method how your application expects to react, so it may change its UI in a meaningful way. Avoid assumptions
    161 about how a software input method should work and just trust it to supply already formatted text to your application.</p>
    162 
    163 <p class="note"><strong>Note:</strong> Android will call event handlers first and then the appropriate default
    164 handlers from the class definition second. As such, returning <em>true</em> from these event listeners will stop
    165 the propagation of the event to other event listeners and will also block the callback to the
    166 default event handler in the View. So be certain that you want to terminate the event when you return <em>true</em>.</p>
    167 
    168 
    169 <h2 id="EventHandlers">Event Handlers</h2>
    170 
    171 <p>If you're building a custom component from  View, then you'll be able to define several callback methods
    172 used as default event handlers.
    173 In the document about <a href="{@docRoot}guide/topics/ui/custom-components.html">Custom
    174 Components</a>, you'll learn see some of the common callbacks used for event handling,
    175 including:</p>
    176 <ul>
    177   <li><code>{@link  android.view.View#onKeyDown}</code> - Called when a new key event occurs.</li>
    178   <li><code>{@link  android.view.View#onKeyUp}</code> - Called when a key up event occurs.</li>
    179   <li><code>{@link  android.view.View#onTrackballEvent}</code> - Called when a trackball motion event occurs.</li>
    180   <li><code>{@link  android.view.View#onTouchEvent}</code> - Called when a touch screen motion event occurs.</li>
    181   <li><code>{@link  android.view.View#onFocusChanged}</code> - Called when the view gains or loses focus.</li>
    182 </ul>
    183 <p>There are some other methods that you should be aware of, which are not part of the View class, 
    184 but can directly impact the way you're able to handle events. So, when managing more complex events inside 
    185 a layout, consider these other methods:</p>
    186 <ul>
    187   <li><code>{@link  android.app.Activity#dispatchTouchEvent(MotionEvent)
    188     Activity.dispatchTouchEvent(MotionEvent)}</code> - This allows your {@link 
    189     android.app.Activity} to intercept all touch events before they are dispatched to the window.</li>
    190   <li><code>{@link  android.view.ViewGroup#onInterceptTouchEvent(MotionEvent)
    191     ViewGroup.onInterceptTouchEvent(MotionEvent)}</code> - This allows a {@link
    192     android.view.ViewGroup} to watch events as they are dispatched to child Views.</li>
    193   <li><code>{@link  android.view.ViewParent#requestDisallowInterceptTouchEvent(boolean)
    194     ViewParent.requestDisallowInterceptTouchEvent(boolean)}</code> - Call this
    195     upon a parent View to indicate that it should not intercept touch events with <code>{@link 
    196     android.view.ViewGroup#onInterceptTouchEvent(MotionEvent)}</code>.</li>
    197 </ul>
    198 
    199 <h2 id="TouchMode">Touch Mode</h2>
    200 <p>
    201 When a user is navigating a user interface with directional keys or a trackball, it is
    202 necessary to give focus to actionable items (like buttons) so the user can see
    203 what will accept input.  If the device has touch capabilities, however, and the user
    204 begins interacting with the interface by touching it, then it is no longer necessary to
    205 highlight items, or give focus to a particular View.  Thus, there is a mode
    206 for interaction named "touch mode." 
    207 </p>
    208 <p>
    209 For a touch-capable device, once the user touches the screen, the device
    210 will enter touch mode.  From this point onward, only Views for which
    211 {@link android.view.View#isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
    212 Other Views that are touchable, like buttons, will not take focus when touched; they will
    213 simply fire their on-click listeners when pressed.
    214 </p>
    215 <p>
    216 Any time a user hits a directional key or scrolls with a trackball, the device will
    217 exit touch mode, and find a view to take focus. Now, the user may resume interacting
    218 with the user interface without touching the screen.
    219 </p>
    220 <p>
    221 The touch mode state is maintained throughout the entire system (all windows and activities). 
    222 To query the current state, you can call
    223 {@link android.view.View#isInTouchMode} to see whether the device is currently in touch mode.
    224 </p>
    225 
    226 
    227 <h2 id="HandlingFocus">Handling Focus</h2>
    228 
    229 <p>The framework will handle routine focus movement in response to user input.
    230 This includes changing the focus as Views are removed or hidden, or as new
    231 Views become available. Views indicate their willingness to take focus
    232 through the <code>{@link android.view.View#isFocusable()}</code> method. To change whether a View can take
    233 focus, call <code>{@link android.view.View#setFocusable(boolean) setFocusable()}</code>.  When in touch mode,
    234 you may query whether a View allows focus with <code>{@link android.view.View#isFocusableInTouchMode()}</code>.
    235 You can change this with <code>{@link android.view.View#setFocusableInTouchMode(boolean) setFocusableInTouchMode()}</code>.
    236 </p>
    237 
    238 <p>Focus movement is based on an algorithm which finds the nearest neighbor in a
    239 given direction. In rare cases, the default algorithm may not match the
    240 intended behavior of the developer. In these situations, you can provide
    241 explicit overrides with the following XML attributes in the layout file:
    242 <var>nextFocusDown</var>, <var>nextFocusLeft</var>, <var>nextFocusRight</var>, and
    243 <var>nextFocusUp</var>. Add one of these attributes to the View <em>from</em> which
    244 the focus is leaving. Define the value of the attribute to be the id of the View
    245 <em>to</em> which focus should be given. For example:</p>
    246 <pre>
    247 &lt;LinearLayout
    248     android:orientation="vertical"
    249     ... >
    250   &lt;Button android:id="@+id/top"
    251           android:nextFocusUp="@+id/bottom"
    252           ... />
    253   &lt;Button android:id="@+id/bottom"
    254           android:nextFocusDown="@+id/top"
    255           ... />
    256 &lt;/LinearLayout>
    257 </pre>
    258 
    259 <p>Ordinarily, in this vertical layout, navigating up from the first Button would not go
    260 anywhere, nor would navigating down from the second Button. Now that the top Button has
    261 defined the bottom one as the <var>nextFocusUp</var> (and vice versa), the navigation focus will 
    262 cycle from top-to-bottom and bottom-to-top.</p>
    263 
    264 <p>If you'd like to declare a View as focusable in your UI (when it is traditionally not), 
    265 add the <code>android:focusable</code> XML attribute to the View, in your layout declaration.
    266 Set the value <var>true</var>. You can also declare a View
    267 as focusable while in Touch Mode with <code>android:focusableInTouchMode</code>.</p>
    268 <p>To request a particular View to take focus, call <code>{@link android.view.View#requestFocus()}</code>.</p>
    269 <p>To listen for focus events (be notified when a View receives or looses focus), use
    270 <code>{@link android.view.View.OnFocusChangeListener#onFocusChange(View,boolean) onFocusChange()}</code>,
    271 as discussed in the <a href="#EventListeners">Event Listeners</a> section, above.</p>
    272 
    273 
    274 
    275 <!--
    276 <h2 is="EventCycle">Event Cycle</h2>
    277    <p>The basic cycle of a View is as follows:</p>
    278    <ol>
    279     <li>An event comes in and is dispatched to the appropriate View. The View
    280     handles the event and notifies any listeners.</li>
    281     <li>If, in the course of processing the event, the View's bounds may need
    282     to be changed, the View will call {@link android.view.View#requestLayout()}.</li>
    283     <li>Similarly, if in the course of processing the event the View's appearance
    284     may need to be changed, the View will call {@link android.view.View#invalidate()}.</li>
    285     <li>If either {@link android.view.View#requestLayout()} or {@link android.view.View#invalidate()} were called,
    286     the framework will take care of measuring, laying out, and drawing the tree
    287     as appropriate.</li>
    288    </ol>
    289    
    290    <p class="note"><strong>Note:</strong> The entire View tree is single threaded. You must always be on
    291    the UI thread when calling any method on any View.
    292    If you are doing work on other threads and want to update the state of a View
    293    from that thread, you should use a {@link android.os.Handler}.
    294    </p>
    295 -->
    296