Thursday, 28 August 2014

Fully Customized Components Android 4.0 by Quontra Solutions

Fully customized components can be used to create graphical components that appear however you wish. Perhaps a graphical VU meter that looks like an old analog gauge, or a sing-a-long text view where a bouncing ball moves along the words so you can sing along with a karaoke machine. Either way, you want something that the built-in components just won't do, no matter how you combine them.
Fortunately, you can easily create components that look and behave in any way you like, limited perhaps only by your imagination, the size of the screen, and the available processing power (remember that ultimately your application might have to run on something with significantly less power than your desktop workstation).
To create a fully customized component:
  1. The most generic view you can extend is, unsurprisingly, View, so you will usually start by extending this to create your new super component.
  2. You can supply a constructor which can take attributes and parameters from the XML, and you can also consume your own such attributes and parameters (perhaps the color and range of the VU meter, or the width and damping of the needle, etc.)
  3. You will probably want to create your own event listeners, property accessors and modifiers, and possibly more sophisticated behavior in your component class as well.
  4. You will almost certainly want to override onMeasure() and are also likely to need to override onDraw() if you want the component to show something. While both have default behavior, the default onDraw() will do nothing, and the default onMeasure() will always set a size of 100x100 — which is probably not what you want.
  5. Other on... methods may also be overridden as required.

Extend onDraw() and onMeasure()

The onDraw() method delivers you a Canvas upon which you can implement anything you want: 2D graphics, other standard or custom components, styled text, or anything else you can think of.


Compound Controls in Custom Components of Android development by Quontr Aolutions

If you don't want to create a completely customized component, but instead are looking to put together a reusable component that consists of a group of existing controls, then creating a Compound Component (or Compound Control) might fit the bill. In a nutshell, this brings together a number of more atomic controls (or views) into a logical group of items that can be treated as a single thing. For example, a Combo Box can be thought of as a combination of a single line EditText field and an adjacent button with an attached PopupList. If you press the button and select something from the list, it populates the EditText field, but the user can also type something directly into the EditText if they prefer.
In Android, there are actually two other Views readily available to do this: Spinner and AutoCompleteTextView, but regardless, the concept of a Combo Box makes an easy-to-understand example.
To create a compound component:
  1. The usual starting point is a Layout of some kind, so create a class that extends a Layout. Perhaps in the case of a Combo box we might use a LinearLayout with horizontal orientation. Remember that other layouts can be nested inside, so the compound component can be arbitrarily complex and structured. Note that just like with an Activity, you can use either the declarative (XML-based) approach to creating the contained components, or you can nest them programmatically from your code.
  2. In the constructor for the new class, take whatever parameters the superclass expects, and pass them through to the superclass constructor first. Then you can set up the other views to use within your new component; this is where you would create the EditText field and the PopupList. Note that you also might introduce your own attributes and parameters into the XML that can be pulled out and used by your constructor.
  3. You can also create listeners for events that your contained views might generate, for example, a listener method for the List Item Click Listener to update the contents of the EditText if a list selection is made.
  4. You might also create your own properties with accessors and modifiers, for example, allow the EditText value to be set initially in the component and query for its contents when needed.
  5. In the case of extending a Layout, you don't need to override the onDraw() and onMeasure() methods since the layout will have default behavior that will likely work just fine. However, you can still override them if you need to.
  6. You might override other on... methods, like onKeyDown(), to perhaps choose certain default values from the popup list of a combo box when a certain key is pressed.
To summarize, the use of a Layout as the basis for a Custom Control has a number of advantages, including:
  • You can specify the layout using the declarative XML files just like with an activity screen, or you can create views programmatically and nest them into the layout from your code.
  • The onDraw() and onMeasure() methods (plus most of the other on... methods) will likely have suitable behavior so you don't have to override them.
  • In the end, you can very quickly construct arbitrarily complex compound views and re-use them as if they were a single component.

Examples of Compound Controls

In the API Demos project that comes with the SDK, there are two List examples — Example 4 and Example 6 under Views/Lists demonstrate a SpeechView which extends LinearLayout to make a component for displaying Speech quotes. The corresponding classes in the sample code are List4.java and List6.java.

Modifying an Existing View Type in Android


There is an even easier option for creating a custom View which is useful in certain circumstances. If there is a component that is already very similar to what you want, you can simply extend that component and just override the behavior that you want to change. You can do all of the things you would do with a fully customized component, but by starting with a more specialized class in the View hierarchy, you can also get a lot of behavior for free that probably does exactly what you want.
For example, the SDK includes a NotePad application in the samples. This demonstrates many aspects of using the Android platform, among them is extending an EditText View to make a lined notepad. This is not a perfect example, and the APIs for doing this might change from this early preview, but it does demonstrate the principles.
If you haven't done so already, import the NotePad sample into Eclipse (or just look at the source using the link provided). In particular look at the definition of MyEditText in the NoteEditor.java file.
Some points to note here
  1. The DefinitionThe class is defined with the following line:
    public static class MyEditText extends EditText
    • It is defined as an inner class within the NoteEditor activity, but it is public so that it could be accessed as NoteEditor.MyEditText from outside of the NoteEditor class if desired.
    • It is static, meaning it does not generate the so-called "synthetic methods" that allow it to access data from the parent class, which in turn means that it really behaves as a separate class rather than something strongly related to NoteEditor. This is a cleaner way to create inner classes if they do not need access to state from the outer class, keeps the generated class small, and allows it to be used easily from other classes.
    • It extends EditText, which is the View we have chosen to customize in this case. When we are finished, the new class will be able to substitute for a normal EditText view.
  2. Class InitializationAs always, the super is called first. Furthermore, this is not a default constructor, but a parameterized one. The EditText is created with these parameters when it is inflated from an XML layout file, thus, our constructor needs to both take them and pass them to the superclass constructor as well.
  3. Overridden MethodsIn this example, there is only one method to be overridden: onDraw() — but there could easily be others needed when you create your own custom components.For the NotePad sample, overriding the onDraw() method allows us to paint the blue lines on the EditText view canvas (the canvas is passed into the overridden onDraw() method). The super.onDraw() method is called before the method ends. The superclass method should be invoked, but in this case, we do it at the end after we have painted the lines we want to include.
  4. Use the Custom ComponentWe now have our custom component, but how can we use it? In the NotePad example, the custom component is used directly from the declarative layout, so take a look at note_editor.xml in the res/layout folder.
    <view
      class="com.android.notepad.NoteEditor$MyEditText" 
      id="@+id/note"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:background="@android:drawable/empty"
      android:padding="10dip"
      android:scrollbars="vertical"
      android:fadingEdge="vertical"/>
    • The custom component is created as a generic view in the XML, and the class is specified using the full package. Note also that the inner class we defined is referenced using the NoteEditor$MyEditText notation which is a standard way to refer to inner classes in the Java programming language.If your custom View component is not defined as an inner class, then you can, alternatively, declare the View component with the XML element name, and exclude the class attribute. For example:
      <com.android.notepad.MyEditText
        id="@+id/note"
        ... />
      Notice that the MyEditText class is now a separate class file. When the class is nested in the NoteEditor class, this technique will not work.
    • The other attributes and parameters in the definition are the ones passed into the custom component constructor, and then passed through to the EditText constructor, so they are the same parameters that you would use for an EditText view. Note that it is possible to add your own parameters as well, and we will touch on this again below.
And that's all there is to it. Admittedly this is a simple case, but that's the point — creating custom components is only as complicated as you need it to be.
A more sophisticated component may override even more on... methods and introduce some of its own helper methods, substantially customizing its properties and behavior. The only limit is your imagination and what you need the component to do.

Building Accessible Custom Views in Android Apps


If your application requires a custom view component, you must do some additional work to ensure that your custom view is accessible. These are the main tasks for ensuring the accessibility of your view:
  • Handle directional controller clicks
  • Implement accessibility API methods
  • Send AccessibilityEvent objects specific to your custom view
  • Populate AccessibilityEvent and AccessibilityNodeInfo for your view

Handling directional controller clicks

On most devices, clicking a view using a directional controller sends a KeyEvent with KEYCODE_DPAD_CENTER to the view currently in focus. All standard Android views already handle KEYCODE_DPAD_CENTER appropriately. When building a custom View control, make sure this event has the same effect as touching the view on the touchscreen.
Your custom control should also treat the KEYCODE_ENTER event the same as KEYCODE_DPAD_CENTER. This approach makes interaction from a full keyboard much easier for users.

Implementing accessibility API methods

Accessibility events are messages about users interaction with visual interface components in your application. These messages are handled by Accessibility Services, which use the information in these events to produce supplemental feedback and prompts. In Android 4.0 (API Level 14) and higher, the methods for generating accessibility events have been expanded to provide more detailed information than the AccessibilityEventSource interface introduced in Android 1.6 (API Level 4). The expanded accessibility methods are part of the View class as well as the View.AccessibilityDelegate class. The methods are as follows:
sendAccessibilityEvent()
(API Level 4) This method is called when a user takes action on a view. The event is classified with a user action type such as TYPE_VIEW_CLICKED. You typically do not need to implement this method unless you are creating a custom view.
sendAccessibilityEventUnchecked()
(API Level 4) This method is used when the calling code needs to directly control the check for accessibility being enabled on the device (AccessibilityManager.isEnabled()). If you do implement this method, you must perform the call as if accessibility is enabled, regardless of the actual system setting. You typically do not need to implement this method for a custom view.
dispatchPopulateAccessibilityEvent()
(API Level 4) The system calls this method when your custom view generates an accessibility event. As of API Level 14, the default implementation of this method calls onPopulateAccessibilityEvent() for this view and then the dispatchPopulateAccessibilityEvent() method for each child of this view. In order to support accessibility services on revisions of Android prior to 4.0 (API Level 14) you must override this method and populate getText() with descriptive text for your custom view, which is spoken by accessibility services, such as TalkBack.
onPopulateAccessibilityEvent()
(API Level 14) This method sets the spoken text prompt of the AccessibilityEvent for your view. This method is also called if the view is a child of a view which generates an accessibility event.
Note: Modifying additional attributes beyond the text within this method potentially overwrites properties set by other methods. While you can modify attributes of the accessibility event with this method, you should limit these changes to text content, and use the onInitializeAccessibilityEvent() method to modify other properties of the event.
Note: If your implementation of this event completely overrides the output text without allowing other parts of your layout to modify its content, then do not call the super implementation of this method in your code.
onInitializeAccessibilityEvent()
(API Level 14) The system calls this method to obtain additional information about the state of the view, beyond text content. If your custom view provides interactive control beyond a simple TextView or Button, you should override this method and set the additional information about your view into the event using this method, such as password field type, checkbox type or states that provide user interaction or feedback. If you do override this method, you must call its super implementation and then only modify properties that have not been set by the super class.
onInitializeAccessibilityNodeInfo()
(API Level 14) This method provides accessibility services with information about the state of the view. The default View implementation has a standard set of view properties, but if your custom view provides interactive control beyond a simple TextView or Button, you should override this method and set the additional information about your view into the AccessibilityNodeInfo object handled by this method.
onRequestSendAccessibilityEvent()
(API Level 14) The system calls this method when a child of your view has generated an AccessibilityEvent. This step allows the parent view to amend the accessibility event with additional information. You should implement this method only if your custom view can have child views and if the parent view can provide context information to the accessibility event that would be useful to accessibility services.
In order to support these accessibility methods for a custom view, you should take one of the following approaches:
  • If your application targets Android 4.0 (API level 14) and higher, override and implement the accessibility methods listed above directly in your custom view class.
  • If your custom view is intended to be compatible with Android 1.6 (API Level 4) and above, add the Android Support Library, revision 5 or higher, to your project. Then, within your custom view class, call the ViewCompat.setAccessibilityDelegate() method to implement the accessibility methods above. For an example of this approach, see the Android Support Library (revision 5 or higher) sample AccessibilityDelegateSupportActivity in (<sdk>/extras/android/support/v4/samples/Support4Demos/)
In either case, you should implement the following accessibility methods for your custom view class:
  • dispatchPopulateAccessibilityEvent()
  • onPopulateAccessibilityEvent()
  • onInitializeAccessibilityEvent()
  • onInitializeAccessibilityNodeInfo()
For more information about implementing these methods, see Populating Accessibility Events.

Sending accessibility events

Depending on the specifics of your custom view, it may need to send AccessibilityEvent objects at a different times or for events not handled by the default implementation. The View class provides a default implementation for these event types:
  • Starting with API Level 4:
    • TYPE_VIEW_CLICKED
    • TYPE_VIEW_LONG_CLICKED
    • TYPE_VIEW_FOCUSED
  • Starting with API Level 14:
    • TYPE_VIEW_SCROLLED
    • TYPE_VIEW_HOVER_ENTER
    • TYPE_VIEW_HOVER_EXIT

Using Platform Styles and Themes in Android 4.0 by Quontra Solutions

The Android platform provides a large collection of styles and themes that you can use in your applications. You can find a reference of all available styles in the R.style class. To use the styles listed here, replace all underscores in the style name with a period. For example, you can apply the Theme_NoTitleBar theme with "@android:style/Theme.NoTitleBar".
The R.style reference, however, is not well documented and does not thoroughly describe the styles, so viewing the actual source code for these styles and themes will give you a better understanding of what style properties each one provides. For a better reference to the Android styles and themes, see the following source code:
  • Android Styles (styles.xml)
  • Android Themes (themes.xml)
These files will help you learn through example. For instance, in the Android themes source code, you'll find a declaration for <style name="Theme.Dialog">. In this definition, you'll see all of the properties that are used to style dialogs that are used by the Android framework.
For more information about the syntax for styles and themes in XML, see the Style Resource document.
For a reference of available style attributes that you can use to define a style or theme (e.g., "windowBackground" or "textAppearance"), see R.attr or the respective View class for which you are creating a style.

Applying Styles and Themes to the UI in Android 4.0 by Quontra Solutions

There are two ways to set a style:
  • To an individual View, by adding the style attribute to a View element in the XML for your layout.
  • Or, to an entire Activity or application, by adding the android:theme attribute to the <activity> or <application> element in the Android manifest.
When you apply a style to a single View in the layout, the properties defined by the style are applied only to that View. If a style is applied to a ViewGroup, the child View elements will not inherit the style properties—only the element to which you directly apply the style will apply its properties. However, you can apply a style so that it applies to all View elements—by applying the style as a theme.
To apply a style definition as a theme, you must apply the style to an Activity or application in the Android manifest. When you do so, every View within the Activity or application will apply each property that it supports. For example, if you apply the CodeFont style from the previous examples to an Activity, then all View elements that support the text style properties will apply them. Any View that does not support the properties will ignore them. If a View supports only some of the properties, then it will apply only those properties.

Apply a style to a View

Here's how to set a style for a View in the XML layout:
<TextView
    style="@style/CodeFont"
    android:text="@string/hello"/>
Now this TextView will be styled as defined by the style named CodeFont. (See the sample above, in Defining Styles.)
Note: The style attribute does not use the android: namespace prefix.

Apply a theme to an Activity or application

To set a theme for all the activities of your application, open the AndroidManifest.xml file and edit the <application> tag to include the android:theme attribute with the style name. For example:
<applicationandroid:theme="@style/CustomTheme">
If you want a theme applied to just one Activity in your application, then add the android:theme attribute to the <activity> tag instead.
Just as Android provides other built-in resources, there are many pre-defined themes that you can use, to avoid writing them yourself. For example, you can use the Dialog theme and make your Activity appear like a dialog box:
<activityandroid:theme="@android:style/Theme.Dialog">
Or if you want the background to be transparent, use the Translucent theme:
<activityandroid:theme="@android:style/Theme.Translucent">
If you like a theme, but want to tweak it, just add the theme as the parent of your custom theme. For example, you can modify the traditional light theme to use your own color like this:
<colorname="custom_theme_color">#b0b0ff</color><stylename="CustomTheme"parent="android:Theme.Light">
    <item name="android:windowBackground">@color/custom_theme_color</item>
    <item name="android:colorBackground">@color/custom_theme_color</item></style>
(Note that the color needs to supplied as a separate resource here because the android:windowBackground attribute only supports a reference to another resource; unlike android:colorBackground, it can not be given a color literal.)
Now use CustomTheme instead of Theme.Light inside the Android Manifest:
<activityandroid:theme="@style/CustomTheme">

Select a theme based on platform version

Newer versions of Android have additional themes available to applications, and you might want to use these while running on those platforms while still being compatible with older versions. You can accomplish this through a custom theme that uses resource selection to switch between different parent themes, based on the platform version.
For example, here is the declaration for a custom theme which is simply the standard platforms default light theme. It would go in an XML file under res/values (typically res/values/styles.xml):
<stylename="LightThemeSelector"parent="android:Theme.Light">
    ...</style>
To have this theme use the newer holographic theme when the application is running on Android 3.0 (API Level 11) or higher, you can place an alternative declaration for the theme in an XML file in res/values-v11, but make the parent theme the holographic theme:
<stylename="LightThemeSelector"parent="android:Theme.Holo.Light">
    ...</style>
Now use this theme like you would any other, and your application will automatically switch to the holographic theme if running on Android 3.0 or higher.
A list of the standard attributes that you can use in themes can be found at R.styleable.Theme.
For more information about providing alternative resources, such as themes and layouts, based on the platform version or other device configurations, see the Providing Resources document.

Defining Styles in Android by Quontra Solutions

To create a set of styles, save an XML file in the res/values/ directory of your project. The name of the XML file is arbitrary, but it must use the .xml extension and be saved in the res/values/ folder.
The root node of the XML file must be <resources>.
For each style you want to create, add a <style> element to the file with a name that uniquely identifies the style (this attribute is required). Then add an <item> element for each property of that style, with a name that declares the style property and a value to go with it (this attribute is required). The value for the <item> can be a keyword string, a hex color, a reference to another resource type, or other value depending on the style property. Here's an example file with a single style:
<?xml version="1.0" encoding="utf-8"?><resources>
    <stylename="CodeFont"parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#00FF00</item>
        <item name="android:typeface">monospace</item>
    </style></resources>
Each child of the <resources> element is converted into an application resource object at compile-time, which can be referenced by the value in the <style> element's name attribute. This example style can be referenced from an XML layout as @style/CodeFont (as demonstrated in the introduction above).
The parent attribute in the <style> element is optional and specifies the resource ID of another style from which this style should inherit properties. You can then override the inherited style properties if you want to.
Remember, a style that you want to use as an Activity or application theme is defined in XML exactly the same as a style for a View. A style such as the one defined above can be applied as a style for a single View or as a theme for an entire Activity or application. How to apply a style for a single View or as an application theme is discussed later.

Inheritance

The parent attribute in the <style> element lets you specify a style from which your style should inherit properties. You can use this to inherit properties from an existing style and then define only the properties that you want to change or add. You can inherit from styles that you've created yourself or from styles that are built into the platform. For example, you can inherit the Android platform's default text appearance and then modify it:
    <stylename="GreenText"parent="@android:style/TextAppearance">
        <item name="android:textColor">#00FF00</item>
    </style>
If you want to inherit from styles that you've defined yourself, you do not have to use the parent attribute. Instead, just prefix the name of the style you want to inherit to the name of your new style, separated by a period. For example, to create a new style that inherits the CodeFont style defined above, but make the color red, you can author the new style like this:
    <stylename="CodeFont.Red">
        <item name="android:textColor">#FF0000</item>
    </style>
Notice that there is no parent attribute in the <style> tag, but because the name attribute begins with the CodeFont style name (which is a style that you have created), this style inherits all style properties from that style. This style then overrides the android:textColor property to make the text red. You can reference this new style as @style/CodeFont.Red.
You can continue inheriting like this as many times as you'd like, by chaining names with periods. For example, you can extend CodeFont.Red to be bigger, with:
    <stylename="CodeFont.Red.Big">
        <item name="android:textSize">30sp</item>
    </style>
This inherits from both CodeFont and CodeFont.Red styles, then adds the android:textSize property.
Note: This technique for inheritance by chaining together names only works for styles defined by your own resources. You can't inherit Android built-in styles this way. To reference a built-in style, such as TextAppearance, you must use the parent attribute.

Style Properties

Now that you understand how a style is defined, you need to learn what kind of style properties—defined by the <item> element—are available. You're probably familiar with some already, such as layout_width and textColor. Of course, there are many more style properties you can use.
The best place to find properties that apply to a specific View is the corresponding class reference, which lists all of the supported XML attributes. For example, all of the attributes listed in the table of TextView XML attributes can be used in a style definition for a TextView element (or one of its subclasses). One of the attributes listed in the reference is android:inputType, so where you might normally place the android:inputType attribute in an <EditText> element, like this:
<EditText
    android:inputType="number"
    ... />
You can instead create a style for the EditText element that includes this property:
<stylename="Numbers">
  <item name="android:inputType">number</item>
  ...</style>
So your XML for the layout can now implement this style:
<EditText
    style="@style/Numbers"
    ... />
This simple example may look like more work, but when you add more style properties and factor-in the ability to re-use the style in various places, the pay-off can be huge.
For a reference of all available style properties, see the R.attr reference. Keep in mind that all View objects don't accept all the same style attributes, so you should normally refer to the specific View class for supported style properties. However, if you apply a style to a View that does not support all of the style properties, the View will apply only those properties that are supported and simply ignore the others.
Some style properties, however, are not supported by any View element and can only be applied as a theme. These style properties apply to the entire window and not to any type of View. For example, style properties for a theme can hide the application title, hide the status bar, or change the window's background. These kind of style properties do not belong to any View object. To discover these theme-only style properties, look at the R.attr reference for attributes that begin with window. For instance, windowNoTitle and windowBackground are style properties that are effective only when the style is applied as a theme to an Activity or application. See the next section for information about applying a style as a theme.

Styles and Themes in Android by Quontra Solutions


A style is a collection of properties that specify the look and format for a View or window. A style can specify properties such as height, padding, font color, font size, background color, and much more. A style is defined in an XML resource that is separate from the XML that specifies the layout.
Styles in Android share a similar philosophy to cascading stylesheets in web design—they allow you to separate the design from the content.
For example, by using a style, you can take this layout XML:
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#00FF00"
    android:typeface="monospace"
    android:text="@string/hello"/>
And turn it into this:
<TextView
    style="@style/CodeFont"
    android:text="@string/hello"/>
All of the attributes related to style have been removed from the layout XML and put into a style definition called CodeFont, which is then applied with the style attribute. You'll see the definition for this style in the following section.
A theme is a style applied to an entire Activity or application, rather than an individual View (as in the example above). When a style is applied as a theme, every View in the Activity or application will apply each style property that it supports. For example, you can apply the same CodeFont style as a theme for an Activity and then all text inside that Activity will have green monospace font.


Taking Action for Users in Android 4.0 by Quontra Solutions

Starting with Android 4.0 (API Level 14), accessibility services can act on behalf of users, including changing the input focus and selecting (activating) user interface elements. In Android 4.1 (API Level 16) the range of actions has been expanded to include scrolling lists and interacting with text fields. Accessibility services can also take global actions, such as navigating to the Home screen, pressing the Back button, opening the notifications screen and recent applications list. Android 4.1 also includes a new type of focus, Accessibilty Focus, which makes all visible elements selectable by an accessibility service.
These new capabilities make it possible for developers of accessibility services to create alternative navigation modes such as gesture navigation, and give users with disabilities improved control of their Android devices.

Listening for gestures

Accessibility services can listen for specific gestures and respond by taking action on behalf of a user. This feature, added in Android 4.1 (API Level 16), and requires that your accessibility service request activation of the Explore by Touch feature. Your service can request this activation by setting the flags member of the service’s AccessibilityServiceInfo instance to FLAG_REQUEST_TOUCH_EXPLORATION_MODE, as shown in the following example.
publicclassMyAccessibilityServiceextendsAccessibilityService{
    @Override
    publicvoid onCreate(){
        getServiceInfo().flags =AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE;
    }
    ...}
Once your service has requested activation of Explore by Touch, the user must allow the feature to be turned on, if it is not already active. When this feature is active, your service receives notification of accessibility gestures through your service's onGesture() callback method and can respond by taking actions for the user.

Using accessibility actions

Accessibility services can take action on behalf of users to make interacting with applications simpler and more productive. The ability of accessibility services to perform actions was added in Android 4.0 (API Level 14) and significantly expanded with Android 4.1 (API Level 16).
In order to take actions on behalf of users, your accessibility service must register to receive events from a few or many applications and request permission to view the content of applications by setting the android:canRetrieveWindowContent to true in the service configuration file. When events are received by your service, it can then retrieve the AccessibilityNodeInfo object from the event using getSource(). With the AccessibilityNodeInfo object, your service can then explore the view hierarchy to determine what action to take and then act for the user using performAction().
publicclassMyAccessibilityServiceextendsAccessibilityService{

    @Override
    publicvoid onAccessibilityEvent(AccessibilityEventevent){
        // get the source node of the event
        AccessibilityNodeInfo nodeInfo =event.getSource();

        // Use the event and node information to determine
        // what action to take

        // take action on behalf of the user
        nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);

        // recycle the nodeInfo object
        nodeInfo.recycle();
    }
    ...}
The performAction() method allows your service to take action within an application. If your service needs to perform a global action such as navigating to the Home screen, pressing the Back button, opening the notifications screen or recent applications list, then use the performGlobalAction() method.

Using focus types

Android 4.1 (API Level 16) introduces a new type of user interface focus called Accessibility Focus. This type of focus can be used by accessibility services to select any visible user interface element and act on it. This focus type is different from the more well known Input Focus, which determines what on-screen user interface element receives input when a user types characters, presses Enter on a keyboard or pushes the center button of a D-pad control.
Accessibility Focus is completely separate and independent from Input Focus. In fact, it is possible for one element in a user interface to have Input Focus while another element has Accessibility Focus. The purpose of Accessibility Focus is to provide accessibility services with a method of interacting with any visible element on a screen, regardless of whether or not the element is input-focusable from a system perspective. You can see accessibility focus in action by testing accessibility gestures. For more information about testing this feature, see Testing gesture navigation.


Note: Accessibility services that use Accessibility Focus are responsible for synchronizing the current Input Focus when an element is capable of this type of focus. Services that do not synchronize Input Focus with Accessibility Focus run the risk of causing problems in applications that expect input focus to be in a specific location when certain actions are taken.
An accessibility service can determine what user interface element has Input Focus or Accessibility Focus using the AccessibilityNodeInfo.findFocus() method. You can also search for elements that can be selected with Input Focus using the focusSearch() method. Finally, your accessibility service can set Accessibility Focus using the 

performAction(AccessibilityNodeInfo.ACTION_SET_ACCESSIBILITY_FOCUS) method.

Getting Event Details Android API's by Quontra Solutions

The Android system provides information to accessibility services about the user interface interaction through AccessibilityEvent objects. Prior to Android 4.0, the information available in an accessibility event, while providing a significant amount of detail about a user interface control selected by the user, offered limited contextual information. In many cases, this missing context information might be critical to understanding the meaning of the selected control.
An example of an interface where context is critical is a calendar or day planner. If the user selects a 4:00 PM time slot in a Monday to Friday day list and the accessibility service announces “4 PM”, but does not announce the weekday name, the day of the month, or the month name, the resulting feedback is confusing. In this case, the context of a user interface control is critical to a user who wants to schedule a meeting.
Android 4.0 significantly extends the amount of information that an accessibility service can obtain about an user interface interaction by composing accessibility events based on the view hierarchy. A view hierarchy is the set of user interface components that contain the component (its parents) and the user interface elements that may be contained by that component (its children). In this way, the Android system can provide much richer detail about accessibility events, allowing accessibility services to provide more useful feedback to users.
An accessibility service gets information about an user interface event through an AccessibilityEvent passed by the system to the service’s onAccessibilityEvent() callback method. This object provides details about the event, including the type of object being acted upon, its descriptive text and other details. Starting in Android 4.0 (and supported in previous releases through the AccessibilityEventCompat object in the Support Library), you can obtain additional information about the event using these calls:
  • AccessibilityEvent.getRecordCount() and getRecord(int) - These methods allow you to retrieve the set of AccessibilityRecord objects which contributed to the AccessibilityEvent passed to you by the system. This level of detail provides more context for the event that triggered your accessibility service.
  • AccessibilityEvent.getSource() - This method returns an AccessibilityNodeInfo object. This object allows you to request view layout hierarchy (parents and children) of the component that originated the accessibility event. This feature allows an accessibility service to investigate the full context of an event, including the content and state of any enclosing views or child views.
    Important: The ability to investigate the view hierarchy from an AccessibilityEvent potentially exposes private user information to your accessibility service. For this reason, your service must request this level of access through the accessibility service configuration XML file, by including the canRetrieveWindowContent attribute and setting it to true. If you do not include this setting in your service configuration xml file, calls to getSource() fail.
    Note: In Android 4.1 (API Level 16) and higher, the getSource() method, as well as AccessibilityNodeInfo.getChild() and getParent(), return only view objects that are considered important for accessibility (views that draw content or respond to user actions). If your service requires all views, it can request them by setting the flags member of the service's AccessibilityServiceInfo instance to FLAG_INCLUDE_NOT_IMPORTANT_VIEWS.

Accessibility Service Methods in Android Development by Quontra Solutions

An accessibility service must extend the AccessibilityService class and override the following methods from that class. These methods are presented in the order in which they are called by the Android system, from when the service is started (onServiceConnected()), while it is running (onAccessibilityEvent(), onInterrupt()) to when it is shut down (onUnbind()).
  • onServiceConnected() - (optional) This system calls this method when it successfully connects to your accessibility service. Use this method to do any one-time setup steps for your service, including connecting to user feedback system services, such as the audio manager or device vibrator. If you want to set the configuration of your service at runtime or make one-time adjustments, this is a convenient location from which to call setServiceInfo().
  • onAccessibilityEvent() - (required) This method is called back by the system when it detects an AccessibilityEvent that matches the event filtering parameters specified by your accessibility service. For example, when the user clicks a button or focuses on a user interface control in an application for which your accessibility service is providing feedback. When this happens, the system calls this method, passing the associated AccessibilityEvent, which the service can then interpret and use to provide feedback to the user. This method may be called many times over the lifecycle of your service.
  • onInterrupt() - (required) This method is called when the system wants to interrupt the feedback your service is providing, usually in response to a user action such as moving focus to a different control. This method may be called many times over the lifecycle of your service.
  • onUnbind() - (optional) This method is called when the system is about to shutdown the accessibility service. Use this method to do any one-time shutdown procedures, including de-allocating user feedback system services, such as the audio manager or device vibrator.
These callback methods provide the basic structure for your accessibility service. It is up to you to decide on how to process data provided by the Android system in the form of AccessibilityEvent objects and provide feedback to the user. For more information about getting information from an accessibility event, see the Implementing Accessibility training.

Registering for Accessibility Events in Android

One of the most important functions of the accessibility service configuration parameters is to allow you to specify what types of accessibility events your service can handle. Being able to specify this information enables accessibility services to cooperate with each other, and allows you as a developer the flexibility to handle only specific events types from specific applications. The event filtering can include the following criteria:
  • Package Names - Specify the package names of applications whose accessibility events you want your service to handle. If this parameter is omitted, your accessibility service is considered available to service accessibility events for any application. This parameter can be set in the accessibility service configuration files with the android:packageNames attribute as a comma-separated list, or set using the AccessibilityServiceInfo.packageNames member.

  • Event Types - Specify the types of accessibility events you want your service to handle. This parameter can be set in the accessibility service configuration files with the android:accessibilityEventTypes attribute as a list separated by the | character (for example accessibilityEventTypes="typeViewClicked|typeViewFocused"), or set using the AccessibilityServiceInfo.eventTypes member.

When setting up your accessibility service, carefully consider what events your service is able to handle and only register for those events. Since users can activate more than one accessibility services at a time, your service must not consume events that it is not able to handle. Remember that other services may handle those events in order to improve a user's experience.

http://www.quontrasolutions.com/

Manifest Declarations and Permissions in Android

Accessibility service declaration

In order to be treated as an accessibility service, your application must include the service element (rather than the activity element) within the application element in its manifest. In addition, within the service element, you must also include an accessibility service intent filter. For compatiblity with Android 4.1 and higher, the manifest must also request the BIND_ACCESSIBILITY_SERVICE permission as shown in the following sample:
<application>
  <serviceandroid:name=".MyAccessibilityService"
      android:label="@string/accessibility_service_label"
      android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
    <intent-filter>
      <actionandroid:name="android.accessibilityservice.AccessibilityService"/>
    </intent-filter>
  </service>
  <uses-permissionandroid:name="android.permission.BIND_ACCESSIBILITY_SERVICE"/></application>
These declarations are required for all accessibility services deployed on Android 1.6 (API Level 4) or higher.

Accessibility service configuration

Accessibility services must also provide a configuration which specifies the types of accessibility events that the service handles and additional information about the service. The configuration of an accessibility service is contained in the AccessibilityServiceInfo class. Your service can build and set a configuration using an instance of this class and setServiceInfo() at runtime. However, not all configuration options are available using this method.
Beginning with Android 4.0, you can include a <meta-data> element in your manifest with a reference to a configuration file, which allows you to set the full range of options for your accessibility service, as shown in the following example:
<serviceandroid:name=".MyAccessibilityService">
  ...
  <meta-data
    android:name="android.accessibilityservice"
    android:resource="@xml/accessibility_service_config"/></service>
This meta-data element refers to an XML file that you create in your application’s resource directory (<project_dir>/res/xml/accessibility_service_config.xml). The following code shows example contents for the service configuration file:
<accessibility-servicexmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/accessibility_service_description"
    android:packageNames="com.example.android.apis"
    android:accessibilityEventTypes="typeAllMask"
    android:accessibilityFlags="flagDefault"
    android:accessibilityFeedbackType="feedbackSpoken"
    android:notificationTimeout="100"
    android:canRetrieveWindowContent="true"
    android:settingsActivity="com.example.android.accessibility.ServiceSettingsActivity"/>
For more information about the XML attributes which can be used in the accessibility service configuration file, follow these links to the reference documentation:
  • android:description
  • android:packageNames
  • android:accessibilityEventTypes
  • android:accessibilityFlags
  • android:accessibilityFeedbackType
  • android:notificationTimeout
  • android:canRetrieveWindowContent
  • android:settingsActivity
For more information about which configuration settings can be dynamically set at runtime, see the AccessibilityServiceInfo reference documentation.


Building Accessibility Services in Android Apps

An accessibility service is an application that provides user interface enhancements to assist users with disabilities, or who may temporarily be unable to fully interact with a device. For example, users who are driving, taking care of a young child or attending a very loud party might need additional or alternative interface feedback.
Android provides standard accessibility services, including TalkBack, and developers can create and distribute their own services. This document explains the basics of building an accessibility service.
The ability for you to build and deploy accessibility services was introduced with Android 1.6 (API Level 4) and received significant improvements with Android 4.0 (API Level 14). The Android Support Library was also updated with the release of Android 4.0 to provide support for these enhanced accessibility features back to Android 1.6. Developers aiming for widely compatible accessibility services are encouraged to use the Support Library and develop for the more advanced accessibility features introduced in Android 4.0..



Andrid App's Special Cases and Considerations by Quontra Solutions

  1. Text field hints: For EditText fields, provide an android:hint attribute instead of a content description, to help users understand what content is expected when the text field is empty and allow the contents of the field to be spoken when it is filled.
  2. Custom controls with high visual context: If your application contains a custom control with a high degree of visual context (such as a calendar control), default accessibility services processing may not provide adequate descriptions for users, and you should consider providing a virtual view hierarchy for your control using AccessibilityNodeProvider.
  3. Custom controls and click handling: If a custom control in your application performs specific handling of user touch interaction, such as listening with onTouchEvent(MotionEvent) for MotionEvent.ACTION_DOWN and MotionEvent.ACTION_UP and treating it as a click event, you must trigger an AccessibilityEvent equivalent to a click and provide a way for accessibility services to perform this action for users. For more information, see Handling custom touch events.
  4. Controls that change function: If you have buttons or other controls that change function during the normal activity of a user in your application (for example, a button that changes from Play to Pause), make sure you also change the android:contentDescription of the button appropriately.
  5. Prompts for related controls: Make sure sets of controls which provide a single function, such as the DatePicker, provide useful audio feedback when an user interacts with the individual controls.
  6. Video playback and captioning: If your application provides video playback, it must support captioning and subtitles to assist users who are deaf or hard of hearing. Your video playback controls must also clearly indicate if captioning is available for a video and provide a clear way of enabling captions.
  7. Supplemental accessibility audio feedback: Use only the Android accessibility framework to provide accessibility audio feedback for your app. Accessibility services such as TalkBack should be the only way your application provides accessibility audio prompts to users. Provide the prompting information with a android:contentDescription XML layout attribute or dynamically add it using accessibility framework APIs. For example, if your application takes action that you want to announce to a user, such as automatically turning the page of a book, use the announceForAccessibility(CharSequence) method to have accessibility services speak this information to the user.
  8. Custom controls with complex visual interactions: For custom controls that provide complex or non-standard visual interactions, provide a virtual view hierarchy for your control using AccessibilityNodeProvider that allows accessibility services to provide a simplified interaction model for the user. If this approach is not feasible, consider providing an alternate view that is accessible.
  9. Sets of small controls: If you have controls that are smaller than the minimum recommended touch size in your application screens, consider grouping these controls together using a ViewGroup and providing a android:contentDescription for the group.
  10. Decorative images and graphics: Elements in application screens that are purely decorative and do not provide any content or enable a user action should not have accessibility content descriptions.
www.quontrasolutions.com
 

Accessibility Developer Checklist in Android Apps

Making an application accessible is about a deep commitment to usability, getting the details right and delighting your users. This document provides a checklist of accessibility requirements, recommendations and considerations to help you make sure your application is accessible. Following this checklist does not guarantee your application is accessible, but it's a good place to start.
Creating an accessible application is not just the responsibility of developers. Involve your design and testing folks as well, and make them are aware of the guidelines for these other stages of development:
  • Android Design: Accessibility
  • Accessibility Testing Checklist
In most cases, creating an accessible Android application does not require extensive code restructuring. Rather, it means working through the subtle details of how users interact with your application, so you can provide them with feedback they can sense and understand. This checklist helps you focus on the key development issues to get the details of accessibility right.

Handling custom touch events in Android Apps

Custom view controls may require non-standard touch event behavior. For example, a custom control may use the onTouchEvent(MotionEvent) listener method to detect the ACTION_DOWN and ACTION_UP events and trigger a special click event. In order to maintain compatibility with accessibility services, the code that handles this custom click event must do the following:
  1. Generate an appropriate AccessibilityEvent for the interpreted click action.
  2. Enable accessibility services to perform the custom click action for users who are not able to use a touch screen.
To handle these requirements in an efficient way, your code should override the performClick() method, which must call the super implementation of this method and then execute whatever actions are required by the click event. When the custom click action is detected, that code should then call your performClick() method. The following code example demonstrates this pattern.
classCustomTouchViewextendsView{

    publicCustomTouchView(Context context){
        super(context);
    }

    boolean mDownTouch =false;

    @Override
    publicboolean onTouchEvent(MotionEventevent){
        super.onTouchEvent(event);

        // Listening for the down and up touch events
        switch(event.getAction()){
            caseMotionEvent.ACTION_DOWN:
                mDownTouch =true;
                returntrue;

            caseMotionEvent.ACTION_UP:
                if(mDownTouch){
                    mDownTouch =false;
                    performClick();// Call this method to handle the response, and
                                    // thereby enable accessibility services to
                                    // perform this action for a user who cannot
                                    // click the touchscreen.
                    returntrue;
                }
        }
        returnfalse;// Return false for other touch events
    }

    @Override
    publicboolean performClick(){
        // Calls the super implementation, which generates an AccessibilityEvent
        // and calls the onClick() listener on the view, if any
        super.performClick();

        // Handle the action for the custom click here

        returntrue;
    }}
The pattern shown above makes sure that the custom click event is compatible with accessibility services by using the performClick() method to both generate an accessibility event and provide an entry point for accessibility services to act on behalf of a user to perform this custom click event.

Enabling Focus Navigation in Android

Focus navigation allows users with disabilities to step through user interface controls using a directional controller. Directional controllers can be physical, such as a trackball, directional pad (D-pad) or arrow keys, or virtual, such as the Eyes-Free Keyboard, or the gestures navigation mode available in Android 4.1 and higher. Directional controllers are a primary means of navigation for many Android users.
To ensure that users can navigate your application using only a directional controller, verify that all user interface (UI) input controls in your application can be reached and activated without using the touchscreen. You should also verify that clicking with the center button (or OK button) of a directional controller has the same effect as touching a control that already has focus. For information on testing directional controls, see Testing focus navigation.

Enabling view focus

A user interface element is reachable using directional controls when its android:focusable attribute is set to true. This setting allows users to focus on the element using the directional controls and then interact with it. The user interface controls provided by the Android framework are focusable by default and visually indicate focus by changing the control’s appearance.
Android provides several APIs that let you control whether a user interface control is focusable and even request that a control be given focus:
  • setFocusable()
  • isFocusable()
  • requestFocus()
If a view is not focusable by default, you can make it focusable in your layout file by setting the android:focusable attribute to true or by calling the its setFocusable() method.

Controlling focus order

When users navigate in any direction using directional controls, focus is passed from one user interface element (view) to another, as determined by the focus order. This order is based on an algorithm that finds the nearest neighbor in a given direction. In rare cases, the algorithm may not match the order that you intended or may not be logical for users. In these situations, you can provide explicit overrides to the ordering using the following XML attributes in your layout file:
android:nextFocusDown
Defines the next view to receive focus when the user navigates down.
android:nextFocusLeft
Defines the next view to receive focus when the user navigates left.
android:nextFocusRight
Defines the next view to receive focus when the user navigates right.
android:nextFocusUp
Defines the next view to receive focus when the user navigates up.
The following example XML layout shows two focusable user interface elements where the android:nextFocusDown and android:nextFocusUp attributes have been explicitly set. The TextView is located to the right of the EditText. However, since these properties have been set, the TextView element can now be reached by pressing the down arrow when focus is on the EditText element:
<LinearLayoutandroid:orientation="horizontal"
        ... >
    <EditTextandroid:id="@+id/edit"
        android:nextFocusDown=”@+id/text”
        ... />
    <TextViewandroid:id="@+id/text"
        android:focusable=”true”
        android:text="Hello, I am a focusable TextView"
        android:nextFocusUp=”@id/edit”
        ... /></LinearLayout>
When modifying focus order, be sure that the navigation works as expected in all directions from each user interface control and when navigating in reverse (to get back to where you came from).