Android API Guides --- Text and Input

Source: Internet
Author: User

Android API Guides --- Text and Input
Text and Input
Use the text service to add convenience features, such as copying/Pasting and checking spelling to your application. You can also develop your own text service that provides custom input methods, dictionaries, and spell checks, and you can distribute them to users for applications.
Blog posts
Add voice input to your IME
The new feature in Android 4.0 is voice input: The difference between users is that the recognition results are displayed in the text box while they are still talking. If you are a development input method, you can easily integrate it with voice input.
Voice Input API is Android
We believe that speech can fundamentally change the mobile experience. We would like to invite all android ?? Android SDK is used to integrate the voice input function.
Make multi-touch

The word "multi-touch" gets a few points around and throws it. It is not always clear who is referring to it. For some people, it is about hardware capabilities. For others, it refers to software supported by specific gestures. Whatever you decide to call it, today let's take a look at how to make your app and enjoy a good performance with multiple fingers on the screen.

Copy and Paste

Android provides a clipboard-based framework with powerful copy and paste functions. It supports simple and complex data types, including text strings, complex data structures, text and binary data streams, and even application assets. Simple text data is stored directly in the clipboard, and complex data is stored as a reference for the resolution of the pasted application and the content provider. Copy and paste are all in the application, and the framework is implemented between applications.


As part of the framework uses content providers, this topic assumes that some APIs familiar with Android content providers are described in topic content providers.


Clipboard Frame


When you use the clipboard frame, you convert the data into a clip object, and then the clip object is clipboard in the whole system. The editing object can take three forms:


Text
Text string. You can directly import the string into the clip object and copy it to the clipboard. To paste a string, copy the clip object and string in the clipboard to the storage of your application.
URI
Represents the URI object of any form of Uri. This is mainly used to copy complex data from the content provider. For the data to be copied, You need to copy a Uri object to the clip object and copy the clip object to the clipboard. To paste the data, you get the clip object and get the Uri object, which is parsed as a data source, such as the content provider, and the storage and replication data from the source to the application.
Intention
Intention. This supports copying application shortcuts. Create an intent for the data to be copied, convert it into a clip object, and copy the clip object to the clipboard. To paste the data, you get the clip object, and then copy the intent object to the memory area of your application.
The clipboard has only one clip object. When the application adds a clip object to the clipboard, the previous clip object disappears.


If you want to allow users to paste data to your application, you do not have to process all types of data. Before you paste the options, you can check the data on the clipboard. In addition to a certain data format, the editing object also contains metadata that tells you what MIME types or types are available. This metadata can help you decide ?? Whether your application can do something useful with Clipboard data. For example, if you have an application that mainly processes texts that may contain Uris or intent editing objects.


You can also allow users to paste text in whatever form of data on the clipboard. To do this, you can force the Clipboard data to be converted to text representation and then paste the text. This is the force conversion clipboard text described in section.


Clipboard class


This section describes the classes used by the clipboard framework.


ClipboardManager


In Android, the system clipboard is represented by the global ClipboardManager class. Instead of directly instantiating this class, you will get a reference to it by calling getSystemService (CLIPBOARD_SERVICE.


ClipData, ClipData. Item and ClipDesc ?? Ription


To add data to the clipboard, you can create a description containing a data and a ClipData object of the data. The clipboard has only one ClipData at a time. A ClipData contains ClipDesc ?? Ription object and one or more ClipData. Item objects.


A ClipDesc ?? The ription object contains the fragment metadata. In particular, it contains an array of data for MIME-type fragments. When you put a clip on the clipboard, this array can be used to paste the application, and it can check it to see if they can process any available MIME types.


A ClipData. Item object contains text, URI, or intent data:


Text
A CharSequence.
URI
A uri. This normally contains the URI of the content provider, although any URI is allowed. The application that provides data uploads the URI clipboard. Applications that want to paste data get a URI from the clipboard and use it to access content providers (or other data sources) and retrieve data.
Intention
Intention. This data type allows your application to copy shortcuts to the clipboard. Then, users can paste shortcuts to their applications for future use.
You can add multiple ClipData. Item objects to a clip. This allows you to copy and paste multiple clips as one clip. For example, if you have a list tool that allows you to select multiple projects at the same time, you can copy all the items to the clipboard at a time. To do this, you can separately ClipData. Item for each project, and then add the ClipData. Item object to the ClipData object.


ClipData


This ClipData class creates a single ClipData. Item object and a simple ClipDesc ?? Static convenient method of ription object ClipData object:


NewPlainText (Label, text)
Returns the ClipData object. The text string contained in a single ClipData. Item object. The ClipDesc ?? Set the tag of the ription object. In ClipDesc ?? The single MIME type of ription is MIMETYPE_TEXT_PLAIN.
Use newPlainText () to create a text string clip.


NewUri (parser, Tag, URI)
Returns the ClipData object. A single ClipData. Item object contains a URI. The ClipDesc ?? Set the tag of the ription object. If the URI is the URI of the content (Uri. getScheme () returns content :). This method is used in the ContentResolver provided by the parser to retrieve available MIME types from the content provider and store them in ClipDesc ?? Ription. For a URI that is not the content: URI, This method uses the MIME type MIMETYPE_TEXT_URILIST.
Use newUri () to create a segment from the URI, especially the content: URI.


NewIntent (TAG, intent)
Returns the ClipData object. A single ClipData. Item object contains an intent. The ClipDesc ?? Set the tag of the ription object. Set the MIME type to MIMETYPE_TEXT_INTENT.
Use newIntent () to create a clip from an Intent object.


Force the Clipboard data to be text


Even if your application can only process text, you can use the ClipData. Item. coerceToText conversion method to copy non-text data from the clipboard ().


This method converts the ClipData. Item data to text and returns a CharSequence. The value returned by ClipData. Item. coerceToText () is in the format of ClipData. Item data:


Text
If ClipData. Item is text (getText () is not null), coerceToText () returns text.
URI
If ClipData. Item is a URI (getUri () is not null), coerceToText () tries to use it as a content URI:
If the URI is a content URI and the provider can return a text stream, coerceToText () returns a text stream.
If the URI is a content URI but the supplier does not provide a text stream, coerceToText () returns the URI representation. Is the same, and is returned through Uri. toString.
If the URI is not the URI of the content, the URI representation returned by coerceToText. Is the same, and is returned through Uri. toString.
Intention
If ClipData. Item is an Intent (getIntent () is not null), coerceToText () converts it into an Intent URI and returns it. The representation is the same, which is returned through Intent. toUri (URI_INTENT_SCHEME.
The clipboard framework summarizes the data to be copied in Figure 1. The application uses ClipboardManager on a ClipData object ?? Board clipboard. The ClipData contains one or more ClipData. Item objects, and one ClipDesc ?? Ription object. To paste data, the application obtains ClipData from ClipDesc ?? Ription gets its MIME type, whether it is data obtained from ClipData. Item or the provider through the content mentioned in ClipData. Item.


Figure 1. Android clipboard framework
Copy to clipboard
Copy the data to the clipboard as described above. You get a global ClipboardManager object, create a ClipData object, add the clip description and one or more ClipData objects. the Item object is added to it and ClipData is added against the ClipboardManager object. The detailed process is described below:
If you are using a content URI to copy data, create a content provider.
This notebook sample application is an example of using the copy and paste content provider. The notepad Provider class implements the content Provider. The notepad class defines contracts between suppliers and other applications, including supported MIME types.
Obtain the system clipboard:

...// if the user selects copycase R.id.menu_copy:// Gets a handle to the clipboard service.ClipboardManager clipboard = (ClipboardManager)    getSystemService(Context.CLIPBOARD_SERVICE);
Copy data to a new ClipData object:
For text

// Creates a new text clip to put on the clipboardClipData clip = ClipData.newPlainText("simple text","Hello, World!");
For a URI


This clip is constructed by the URI provider that records the ID of the encoding to the content. This technique is covered in some encoded URI identifiers for more details:

// Creates a Uri based on a base Uri and a record ID based on the contact's last name// Declares the base URI stringprivate static final String CONTACTS = "content://com.example.contacts";// Declares a path string for URIs that you use to copy dataprivate static final String COPY_PATH = "/copy";// Declares the Uri to paste to the clipboardUri copyUri = Uri.parse(CONTACTS + COPY_PATH + "/" + lastName);...// Creates a new URI clip object. The system uses the anonymous getContentResolver() object to// get MIME types from provider. The clip object's label is "URI", and its data is// the Uri previously created.ClipData clip = ClipData.newUri(getContentResolver(),"URI",copyUri);
For intentions


This Code builds an application's intent and then adds it to the clip object:

// Creates the IntentIntent appIntent = new Intent(this, com.example.demo.myapplication.class);...// Creates a clip object with the Intent in it. Its label is "Intent" and its data is// the Intent object created previouslyClipData clip = ClipData.newIntent("Intent",appIntent);
Clipboard the new clip object:

// Set the clipboard's primary clip.clipboard.setPrimaryClip(clip);
Paste from clipboard
As mentioned above, you can obtain the global clipboard object, get the clip object, and view its data and paste the data from the clipboard, if possible, copy the data from the clip object to your own storage. This section describes how to do this for the three types of Clipboard data.
Paste plain text
To paste plain text, first obtain the global clipboard and verify that it can return plain text. Then copy the edited object and the text using getText () to your own storage, as described in the following process:
Obtain the global clipboard management object using getSystemService (CLIPBOARD_SERVICE. Declare a global variable that contains the pasted text:

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);String pasteData = "";
Next, determine whether to enable or disable the paste option for the current activity. You should verify that the Clipboard contains a clip and can process the data type represented by the clip:

/ Gets the ID of the "paste" menu itemMenuItem mPasteItem = menu.findItem(R.id.menu_paste);// If the clipboard doesn't contain data, disable the paste menu item.// If it does contain data, decide if you can handle the data.if (!(clipboard.hasPrimaryClip())) {  mPasteItem.setEnabled(false);  } else if (!(clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN))) {    // This disables the paste menu item, since the clipboard has data but it is not plain text    mPasteItem.setEnabled(false);  } else {    // This enables the paste menu item, since the clipboard contains plain text.    mPasteItem.setEnabled(true);  }}
Copy data from to the clipboard. If the "Paste" menu item is enabled, the scheme will only arrive, so that you can assume that the Clipboard contains plain text. You do not know whether it contains a text string or a URI pointing to plain text. The following code snippet is tested, but it only shows the code that processes the plain text format.

// Responds to the user selecting "paste"case R.id.menu_paste:// Examines the item on the clipboard. If getText() does not return null, the clip item contains the// text. Assumes that this application can only handle one item at a time.ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);// Gets the clipboard as text.pasteData = item.getText();// If the string contains data, then the paste operation is doneif (pasteData != null) {  return;// The clipboard does not contain text. If it contains a URI, attempts to get data from it} else {  Uri pasteUri = item.getUri();  // If the URI contains something, try to get text from it  if (pasteUri != null) {    // calls a routine to resolve the URI and get data from it. This routine is not    // presented here.    pasteData = resolveUri(Uri);    return;  } else {  // Something is wrong. The MIME type was plain text, but the clipboard does not contain either  // text or a Uri. Report an error.  Log.e("Clipboard contains an invalid data type");  return;  }}
Paste data from the content URI
The ClipData. Item object contains the content URI. You have determined that you can process one of its MIME types, create a ContentResolver, and then call the corresponding content provider method to retrieve data.
The following procedure describes how to obtain data from a content provider based on the Content URI on the clipboard. It checks that the application can use the MIME type from the vendor:
Declare a global variable that contains the MIME type:

// Declares a MIME type constant to match against the MIME types offered by the providerpublic static final String MIME_TYPE_CONTACT = "vnd.android.cursor.item/vnd.example.contact"
Obtain the global clipboard. You can also get a ContentResolver, so you can access the content provider:

// Gets a handle to the Clipboard ManagerClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);// Gets a content resolver instanceContentResolver cr = getContentResolver();
Obtain the main clip in the clipboard and obtain the URI:

// Gets the clipboard data from the clipboardClipData clip = clipboard.getPrimaryClip();if (clip != null) {  // Gets the first item from the clipboard data  ClipData.Item item = clip.getItemAt(0);  // Tries to get the item's contents as a URI  Uri pasteUri = item.getUri();
Test to view that the URI is a content URI by calling getType (URI ). If the URI does not point to a valid content provider, this method returns null:

 // If the clipboard contains a URI reference  if (pasteUri != null) {    // Is this a content URI?    String uriMimeType = cr.getType(pasteUri);
Test the MIME type supported by the content provider to view. The current application can understand. In this case, call ContentResolver. query () to obtain data. The returned value is a cursor:

// If the return value is not null, the Uri is a content Uri    if (uriMimeType != null) {      // Does the content provider offer a MIME type that the current application can use?      if (uriMimeType.equals(MIME_TYPE_CONTACT)) {        // Get the data from the content provider.        Cursor pasteCursor = cr.query(uri, null, null, null, null);        // If the Cursor contains data, move to the first record        if (pasteCursor != null) {          if (pasteCursor.moveToFirst()) {          // get the data from the Cursor here. The code will vary according to the          // format of the data model.          }        }        // close the Cursor        pasteCursor.close();      }    }  }}
Paste an Intent


To paste an Intent, first obtain the global clipboard. Check the ClipData. Item object to see if it contains an intent. Then, call getIntent () to copy the intent to your own storage. The following code demonstrates this:

// Gets a handle to the Clipboard ManagerClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);// Checks to see if the clip item contains an Intent, by testing to see if getIntent() returns nullIntent pasteIntent = clipboard.getPrimaryClip().getItemAt(0).getIntent();if (pasteIntent != null) {  // handle the Intent} else {  // ignore the clipboard, or issue an error if your application was expecting an Intent to be  // on the clipboard}
Using content providers to replicate complex data


Content providers support replication, such as complex data in database records or file streams. For the data to be copied, you set the clipboard content URI. Paste the application and obtain the URI from the clipboard and use it to retrieve the data or file stream descriptor in the database.


Since the app only has the URI of your data content, you need to know the data block to be retrieved. You can provide this information by the identifier of the URI itself encoded as the data, or you can provide a unique URI to return the data to be copied. The technical choice depends on the data organization.


The following sections describe how to set the URI, how to provide complex data, and how to provide file streams. This description assumes that you are familiar with the general principles of content provider design.


The identifier of the encoded URI.


To copy data to a URI clipboard, a useful method is to encode the data of the URI itself of the identifier. The content provider can then use the identifier in the URI to retrieve data. You do not have to know the existence of this identifier when pasting an application. All it does is ask you to "Reference" from the clipboard (add the identifier in the URI), give it to the content provider, and retrieve the data.


You usually concatenate the identifier at the end of the URI to encode the URI content. For example, suppose you define your supplier URI as the following string:

"content://com.example.contacts"
If you want to encode the name to this URI, you can use the following code snippet:

String uriString = "content://com.example.contacts" + "/" + "Smith"// uriString now contains content://com.example.contacts/Smith.// Generates a uri object from the string representationUri copyUri = Uri.parse(uriString);
If you have already used the content provider, you may want to add it, indicating that the URI is copying a new URI path. For example, assume that you already have the following URI path:

"content://com.example.contacts"/people"content://com.example.contacts"/people/detail"content://com.example.contacts"/people/images
You can add another path that is specific to the copied URI:

"content://com.example.contacts/copying"
Then, you can detect the "copy" URI and code through pattern matching, and perform specific copy and paste operations.


Generally, if you are already using a content provider, internal database, or internal table to organize the encoding technology used by your data. In these cases, you have multiple works. The data you want to copy is probably the unique identifier of each piece. When you apply for a query by answering and pasting the answer, you can use its identifier to search for the data and return it.


If you do not have multiple data, you may not need to encode the identifier. You can simply use the vendor unique to URI. In response to the query, your supplier returns the data it currently contains.


The upload ID is a record used in the notebook sample application to open a note from the note list. This example uses the _ id field from a SQL database, but you can have the identifier of any number or character you want.


Copy Data Structure


You can copy and paste complex data content providers as subclasses of the ContentProvider component. You should also encode the URI so that you can direct the clipboard to the desired record. In addition, you must consider the current status of your application:


If you already have a content provider, you can add it to its function. You may only need to modify its query () method to process the URI from the application to which the data is to be pasted. You may want to modify the method to process the "copy" URI mode.
If your application maintains an internal database, you may want the database to be moved to the content provider for copying from it.
If you do not currently use a database, you can implement a simple content provider. its only purpose is to provide the data application and paste it from the clipboard.
At the content provider, you must cover at least the following methods:


Query ()
The pasted application will think that they can use this method, and you get data from the URI on the clipboard. To support replication, you should have this method to detect the URI containing a special "copy" path. The application can then create a copy URI on the clipboard, which contains the copy path and an accurate record pointing to the copy.
GetType ()
The MIME type or type returned by this method is your intention to copy the data. This method newUri () to convert the MIME type to the getType () called by the new ClipData object ().
Description of the topic content provider in MIME-type complex data.


Note that there is no need for any other content provider method, such as insert () or update (). To paste an application, you only need to obtain the supported MIME type and copy data from the supplier. If you already have these methods, they will not interfere with the replication operation.


The following code snippet demonsrate how to set your application to copy complex data:


In the global constant of your application, declare the basic URI string to identify the path of the URI string that you are using to copy data. At the same time, the MIME type is declared as replicated data:

// Declares the base URI stringprivate static final String CONTACTS = "content://com.example.contacts";// Declares a path string for URIs that you use to copy dataprivate static final String COPY_PATH = "/copy";// Declares a MIME type for the copied datapublic static final String MIME_TYPE_CONTACT = "vnd.android.cursor.item/vnd.example.contact"
During the activity of copying data from a user, set the code to copy data to the clipboard. In response to a copy request, put the URI clipboard:

public class MyCopyActivity extends Activity {  ...// The user has selected a name and is requesting a copy.case R.id.menu_copy:  // Appends the last name to the base URI  // The name is stored in "lastName"  uriString = CONTACTS + COPY_PATH + "/" + lastName;  // Parses the string into a URI  Uri copyUri = Uri.parse(uriString);  // Gets a handle to the clipboard service.  ClipboardManager clipboard = (ClipboardManager)    getSystemService(Context.CLIPBOARD_SERVICE);  ClipData clip = ClipData.newUri(getContentResolver(), "URI", copyUri);  // Set the clipboard's primary clip.  clipboard.setPrimaryClip(clip);
In the global content provider, create a URI match and add a URI pattern to match the URI on the clipboard:

public class MyCopyProvider extends ContentProvider {  ...// A Uri Match object that simplifies matching content URIs to patterns.private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);// An integer to use in switching based on the incoming URI patternprivate static final int GET_SINGLE_CONTACT = 0;...// Adds a matcher for the content URI. It matches// "content://com.example.contacts/copy/*"sUriMatcher.addURI(CONTACTS, "names/*", GET_SINGLE_CONTACT);
Set query()Method. This method can process different URL modes, depending on how you write code, but only display as the clipboard copy operation mode:

// Sets up your provider's query() method.public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,  String sortOrder) {  ...  // Switch based on the incoming content URI  switch (sUriMatcher.match(uri)) {  case GET_SINGLE_CONTACT:    // query and return the contact for the requested name. Here you would decode    // the incoming URI, query the data model based on the last name, and return the result    // as a Cursor.  ...}
The getType () method is set to return a data copy of the appropriate MIME type:

/ Sets up your provider's getType() method.public String getType(Uri uri) {  ...  switch (sUriMatcher.match(uri)) {  case GET_SINGLE_CONTACT:      return (MIME_TYPE_CONTACT);
This section describes how to obtain the content URI from the clipboard and use it to obtain and paste data.


Copy Data Streams


You can copy and paste a large number of text and binary data streams. The data can take the following forms:


Files stored on the actual device.
Stream from outlet.
A large amount of data is stored in the provider's basic database system.
The data stream content provider provides a file descriptor object to access its data, such as AssetFileDescriptor rather than the cursor object. Paste the application to read data streams using the file descriptor.


To set up your application and supplier to copy data streams, follow these steps:


You set the content URI on the clipboard. The options include:
The URI on the identifier of the encoded data stream, such as the description of the URI identifier in some encoding, and then the table that contains the identifier and the corresponding stream name in the provider.
The name of the URI-encoded stream.
Using a unique URI always returns the current stream provided from. If you use this option, remember to update your vendor and point to different streams when your stream is copied to the URI clipboard.
Provide a MIME type for each type of data stream you plan to provide. This information is required to paste the data on the clipboard.
One of the methods to implement a ContentProvider that returns a file descriptor to a stream. If your content URI is encoded, use this method to determine the stream to be opened.
Copy the data stream to the clipboard, construct the content URI, and place it on the clipboard.
To paste a data stream, an application obtains the clip from the clipboard, obtains the URI, and uses it to call the ContentResolver file descriptor method of the open stream. The ContentResolver calls the corresponding ContentProvider method to pass the content URI. The file descriptor ContentResolver method returned by your vendor. Paste and the application has the responsibility to read data from the stream.


The following list shows the method of the most important file descriptor of the content provider. Each method has a corresponding ContentResolver method and the string "descriptor" appended to the method name. For example, the ContentResolver of openAssetFile () is similar to openAssetFileDescriptor ():


OpenTypedAssetFile ()
This method should return the file descriptor of an asset, but only when the MIME type is supported by the provider. The caller (the application is pasted) provides a MIME-type mode. (An application that has copied a URI to the clipboard) the content provider returns the AssetFileDescriptor file handle if it can provide the MIME type or throw it if it cannot be an exception.
This method is used to process files. You can use it to read the asset that the content provider has copied to the clipboard.


OpenAssetFile ()
This method is a more general form of openTypedAssetFile (). It does not filter the allowed MIME types, but it can read the file section.
Open a file ()
This is a more general form of openAssetFile (). It cannot read the file section.
You can choose to use the openPipeHelper () method and your file descriptor method. This makes the application program paste into the background thread of the MPs queue to read data streams. To use this method, you must implement the ContentProvider. PipeDataWriter interface. This example is given in the notebook sample application, in the openTypedAssetFile () method of NotePadProvider. java.


Design valid copy/Paste functions


To design an effective copy and paste function for your application, remember the following:


At any time, there is only one clip on the clipboard. The new copy operation of any application in the system will overwrite the previous clip. Since you can navigate to your application and make a copy before returning, you cannot assume that the Clipboard contains the clip that you copied before the application.
The expected purpose of Editing Multiple ClipData. Item objects is to support copying and pasting multiple choices, rather than referring to a single choice in different forms. You usually want all ClipData. Item objects in the clip to have the same form, that is, he ?? They should all be simple text, content URI or intent, but not a mixture.
When you provide data, you can provide different MIME representations. Add your ClipDesc ?? Ription supports the MIME type, and then implements the MIME type in the content provider.
When you obtain data from the clipboard, your application is responsible for checking available MIME types and then deciding which one to use, if any, to use. Your applications do not need to be pasted, even with clips and user requests on the clipboard. What you should do, if the MIME type of the post is compatible. You can force the data on the clipboard to use coerceToText () if you select text. If your application supports more than one available MIME type, you can select which one to use.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.