Handling focus

Focus is like a game of tag; one and only one component on the screen is always "it." All devices with Uls support this concept. When you are turning the pages of a book, your focus is on one particular page (or even word or letter) at a time. Computer interfaces are no different. Though there may be many different windows and widgets on a particular screen, only one has the current focus and can respond to user input. An event, such as movement of the mouse, a mouse click, or keyboard press, may trigger the focus to shift to another component.

In Android focus is handled for you by the platform a majority of the time. When a user selects an Activity, it is invoked and the focus is set to the foreground View. Internal Android algorithms then determine where the focus should go next (who should be tagged) based on events (buttons being clicked, menus selected, services returning callbacks, and so on). You can override the default behavior and provide hints about where specifically you want the focus to go using the following View class methods (or their counterparts in XML):

■ nextFocusDown

■ nextFocusLeft

■ nextFocusRight

■ nextFocusUp

Views can also indicate a particular focus type, DEFAULT_FOCUS or WEAK_FOCUS, to set the priority of focus they desire, themselves (default) versus their descendants (weak). In addition to hints, such as UP, DOWN, and WEAK, you can use the View.requestFocus() method directly, if need be, to indicate that focus should be set to a particular View at a given time. Manipulating the focus manually should be the exception rather than the rule (the platform logic generally does what you would expect).

Focus gets changed based on event-handling logic using the OnFocusChange-Listener object and related setOnFocusChangedListener() method. This takes us into the world of event handling in general.

0 0

Post a comment