An input method editor (IME) is a user control that enables users to enter text. Android provides an extensible input method framework that allows ...
Quicknav
Quicknav
Design
Develop
Distribute
GooglePlayDeveloperConsole
AndroidDevelopersBlog
AboutAndroid
Android.com
AndroidDevelopers
AndroidOpenSourceProject
close
GetStarted
Style
Patterns
BuildingBlocks
Downloads
Videos
Training
APIGuides
Reference
Tools
GettheSDK
GoogleServices
GooglePlay
Publishing
Promoting
AppQuality
Spotlight
OpenDistribution
Results
Loading...
Training
APIGuides
Reference
Tools
GoogleServices
totop
AppComponents
AppFundamentals
Activities
Fragments
Loaders
TasksandBackStack
Services
BoundServices
AIDL
ContentProviders
ContentProviderBasics
CreatingaContentProvider
CalendarProvider
ContactsProvider
IntentsandIntentFilters
ProcessesandThreads
Permissions
AppWidgets
AndroidManifest
UserInterface
Overview
Layouts
LinearLayout
RelativeLayout
ListView
GridView
InputControls
Buttons
TextFields
Checkboxes
RadioButtons
ToggleButtons
Spinners
Pickers
InputEvents
Menus
ActionBar
Settings
Dialogs
Notifications
Toasts
Search
CreatingaSearchInterface
AddingRecentQuerySuggestions
AddingCustomSuggestions
SearchableConfiguration
DragandDrop
Accessibility
MakingApplicationsAccessible
AccessibilityDeveloperChecklist
BuildingAccessibilityServices
StylesandThemes
CustomComponents
AppResources
Overview
ProvidingResources
AccessingResources
HandlingRuntimeChanges
Localization
ResourceTypes
Animation
ColorStateList
Drawable
Layout
Menu
String
Style
MoreTypes
AnimationandGraphics
Overview
PropertyAnimation
ViewAnimation
DrawableAnimation
CanvasandDrawables
OpenGL
HardwareAcceleration
Computation
Renderscript
AdvancedRenderscript
RuntimeAPIReference
MediaandCamera
MediaPlayback
SupportedMediaFormats
AudioCapture
JetPlayer
Camera
LocationandSensors
LocationandMaps
LocationStrategies
SensorsOverview
MotionSensors
PositionSensors
EnvironmentSensors
Connectivity
Bluetooth
NFC
NFCBasics
AdvancedNFC
Wi-FiDirect
USB
Accessory
Host
SIP
TextandInput
CopyandPaste
CreatinganIME
SpellingChecker
DataStorage
StorageOptions
DataBackup
AppInstallLocation
Administration
DevicePolicies
WebApps
Overview
TargetingScreensfromWebApps
BuildingWebAppsinWebView
DebuggingWebApps
BestPracticesforWebApps
BestPractices
BewährteVerfahren
Prácticasrecomendadas
Meilleurespratiques
Bestpractice
ベストプラクティス
最佳实践
最佳實務
Compatibility
SupportingMultipleScreens
DistributingtoSpecificScreens
ScreenCompatibilityMode
SupportingTabletsandHandsets
CreatinganInputMethod
Seealso
OnscreenInputMethods
SoftKeyboardsample
Aninputmethodeditor(IME)isausercontrolthatenablesuserstoentertext.Android
providesanextensibleinputmethodframeworkthatallowsapplicationstoprovideusers
alternativeinputmethods,suchason-screenkeyboardsorevenspeechinput.Onceinstalled,
userscanselectwhichIMEtheywanttousefromthesystemsettingsanduseitacrossthe
entiresystem;onlyoneIMEmaybeenabledatatime.
ToaddanIMEtotheAndroidsystem,youcreateanAndroidapplication
containingaclassthatextendsInputMethodService.In
addition,youusuallycreatea"settings"activitythatpassesoptionstotheIME
service.YoucanalsodefineasettingsUIthat'sdisplayedaspartofthesystemsettings.
Thisarticlecoversthefollowing:
TheIMElifecycle.
DeclaringIMEcomponentsintheapplicationmanifest.
TheIMEAPI.
DesigninganIMEUI.
SendingtextfromanIMEtoanapplication.
WorkingwithIMEsubtypes.
Ifyouhaven'tworkedwithIMEsbefore,youshouldreadtheintroductoryarticle
OnscreenInputMethodsfirst.
Also,theSoftKeyboardsampleappincludedintheSDKcontainssamplecodethatyoucanmodify
tostartbuildingyourownIME.
TheIMELifecycle
ThefollowingdiagramdescribesthelifecycleofanIME:
Figure1.ThelifecycleofanIME.
ThefollowingsectionsdescribehowtoimplementtheUIandcodeassociatedwithanIMEthat
followsthislifecycle.
DeclaringIMEComponentsintheManifest
IntheAndroidsystem,anIMEisanAndroidapplicationthatcontainsaspecialIMEservice.
Theapplication'smanifestfilemustdeclaretheservice,requestthenecessarypermissions,
provideanintentfilterthatmatchestheactionaction.view.InputMethod,and
providemetadatathatdefinescharacteristicsoftheIME.Inaddition,toprovideasettings
interfacethatallowstheusertomodifythebehavioroftheIME,youcandefinea"settings"
activitythatcanbelaunchedfromSystemSettings.
ThefollowingsnippetdeclaresIMEservice.ItrequeststhepermissionBIND_INPUT_METHODtoallowtheservicetoconnecttheIMEto
thesystem,setsupanintentfilterthatmatchestheaction
android.view.InputMethod,anddefinesmetadatafortheIME:
ThisnextsnippetdeclaresthesettingsactivityfortheIME.Ithasanintentfilterfor
ACTION_MAINthatindicatesthisactivityisthemainentrypoint
fortheIMEapplication:
YoucanalsoprovideaccesstotheIME'ssettingsdirectlyfromitsUI.
TheInputMethodAPI
ClassesspecifictoIMEsarefoundintheandroid.inputmethodserviceandandroid.view.inputmethodpackages.TheKeyEventclassisimportantfor
handlingkeyboardcharacters.
ThecentralpartofanIMEisaservicecomponent,aclassthatextends
InputMethodService.Inadditiontoimplementingthe
normalservicelifecycle,thisclasshascallbacksforprovidingyourIME'sUI,handlinguser
input,anddeliveringtexttothefieldthatcurrentlyhasfocus.Bydefault,the
InputMethodServiceclassprovidesmostoftheimplementation
formanagingthestateandvisibilityoftheIMEandcommunicatingwiththecurrent
inputfield.
Thefollowingclassesarealsoimportant:
BaseInputConnection
DefinesthecommunicationchannelfromanInputMethod
backtotheapplicationthatisreceivingitsinput.Youuseittoreadtextaroundthe
cursor,committexttothetextbox,andsendrawkeyeventstotheapplication.
Applicationsshouldextendthisclassratherthanimplementingthebaseinterface
InputConnection.
KeyboardView
AnextensionofViewthatrendersakeyboardandrespondstouser
inputevents.Thekeyboardlayoutisspecifiedbyaninstanceof
Keyboard,whichyoucandefineinanXMLfile.
DesigningtheInputMethodUI
TherearetwomainvisualelementsforanIME:theinputviewandthe
candidatesview.Youonlyhavetoimplementtheelementsthatarerelevantto
theinputmethodyou'redesigning.
Inputview
TheinputviewistheUIwheretheuserinputstext,intheformofkeyclicks,handwritingor
gestures.WhentheiIMEisdisplayedforthefirsttime,thesystemcallsthe
onCreateInputView()callback.Inyour
implementationofthismethod,youcreatethelayoutyouwanttodisplayintheIME
windowandreturnthelayouttothesystem.Thissnippetisanexampleofimplementingthe
onCreateInputView()method:
@Override
publicViewonCreateInputView(){
MyKeyboardViewinputView=
(MyKeyboardView)getLayoutInflater().inflate(R.layout.input,null);
inputView.setOnKeyboardActionListener(this);inputView.setKeyboard(mLatinKeyboard);
returnmInputView;
}
Inthisexample,MyKeyboardViewisaninstanceofacustomimplementationof
KeyboardViewthatrendersa
Keyboard.Ifyou’rebuildingatraditionalQWERTYkeyboard,
seetheSoftKeyboardsample
appforanexampleofhowtoextendtheKeyboardViewclass.
Candidatesview
ThecandidatesviewistheUIwheretheIMEdisplayspotentialwordcorrectionsor
suggestionsfortheusertoselect.IntheIMElifecycle,thesystemcalls
onCreateCandidatesView()whenit'sready
todisplaythecandidateview.Inyourimplementationofthismethod,returnalayoutthatshows
wordsuggestions,orreturnnullifyoudon’twanttoshowanything(anullresponseisthe
defaultbehavior,soyoudon’thavetoimplementthisifyoudon’tprovidesuggestions).
Foranexampleimplementationthatprovidesusersuggestions,seethe
SoftKeyboardsample
app.
UIdesignconsiderations
ThissectiondescribessomespecificUIdesignconsiderationsforIMEs.
Handlingmultiplescreensizes
TheUIforyourIMEmustbeabletoscalefordifferentscreensizes,anditalso
musthandlebothlandscapeandportraitorientations.Innon-fullscreenIMEmode,leave
sufficientspacefortheapplicationtoshowthetextfieldandanyassociatedcontext,sothat
nomorethanhalfthescreenisoccupiedbytheIME.InfullscreenIMEmodethisisnotan
issue.
Handlingdifferentinputtypes
Androidtextfieldsallowyoutosetaspecificinputtype,suchasfreeformtext,numbers,
URLs,emailaddresses,andsearchstrings.WhenyouimplementanewIME,youneedto
detecttheinputtypeofeachfieldandprovidetheappropriateinterfaceforit.However,you
don'thavetosetupyourIMEtocheckthattheuserenteredtextthat'svalidforthe
inputtype;that'stheresponsibilityoftheapplicationthatownsthetextfield.
Forexample,herearescreenshotsoftheinterfacesthattheLatinIMEprovidedwiththe
Androidplatformprovidesfortextandphonenumberinputs:
Figure2.LatinIMEinputtypes.
WhenaninputfieldreceivesfocusandyourIMEstarts,thesystemcalls
onStartInputView(),passinginanEditorInfoobjectthat
containsdetailsabouttheinputtypeandotherattributesofthetextfield.Inthisobject,
theinputTypefieldcontainsthetextfield'sinput
type.
TheinputTypefieldisanint
thatcontainsbitpatternsforvariousinputtypesettings.Totestitforthetextfield's
inputtype,maskitwiththeconstantTYPE_MASK_CLASS,like
this:
inputType&InputType.TYPE_MASK_CLASS
Theinputtypebitpatterncanhaveoneofseveralvalues,including:
TYPE_CLASS_NUMBER
Atextfieldforenteringnumbers.Asillustratedinthepreviousscreenshot,the
LatinIMEdisplaysanumberpadforfieldsofthistype.
TYPE_CLASS_DATETIME
Atextfieldforenteringadateandtime.
TYPE_CLASS_PHONE
Atextfieldforenteringtelephonenumbers.
TYPE_CLASS_TEXT
Atextfieldforenteringallsupportedcharacters.
Theseconstantsaredescribedinmoredetailinthereferencedocumentationfor
InputType.
TheinputTypefieldcancontainotherbitsthat
indicateavariantofthetextfieldtype,suchas:
TYPE_TEXT_VARIATION_PASSWORD
AvariantofTYPE_CLASS_TEXTforenteringpasswords.The
inputmethodwilldisplaydingbatsinsteadoftheactualtext.
TYPE_TEXT_VARIATION_URI
AvariantofTYPE_CLASS_TEXTforenteringwebURLsand
otherUniformResourceIdentifiers(URIs).
TYPE_TEXT_FLAG_AUTO_COMPLETE
AvariantofTYPE_CLASS_TEXTforenteringtextthatthe
application"auto-completes"fromadictionary,search,orotherfacility.
RemembertomaskinputTypewiththeappropriate
constantwhenyoutestforthesevariants.Theavailablemaskconstantsarelistedinthe
referencedocumentationforInputType.
Caution:InyourownIME,makesureyouhandletextcorrectlywhenyousendit
toapasswordfield.HidethepasswordinyourUIbothintheinputviewandinthecandidates
view.Alsorememberthatyoushouldn'tstorepasswordsonadevice.Tolearnmore,seetheDesigningforSecurityguide.
SendingTexttotheApplication
AstheuserinputstextwithyourIME,youcansendtexttotheapplicationby
sendingindividualkeyeventsorbyeditingthetextaroundthecursorintheapplication'stext
field.Ineithercase,youuseaninstanceofInputConnection
todeliverthetext.Togetthisinstance,call
InputMethodService.getCurrentInputConnection().
Editingthetextaroundthecursor
Whenyou'rehandlingtheeditingofexistingtextinatextfield,someofthemoreuseful
methodsinBaseInputConnectionare:
getTextBeforeCursor()
ReturnsaCharSequencecontainingthenumberofrequestedcharacters
beforethecurrentcursorposition.
getTextAfterCursor()
ReturnsaCharSequencecontainingthenumberofrequestedcharacters
followingthecurrentcursorposition.
deleteSurroundingText()
Deletesthespecifiednumberofcharactersbeforeandfollowingthecurrentcursor
position.
commitText()
CommitaCharSequencetothetextfieldandsetanewcursor
position.
Forexample,thefollowingsnippetshowshowtoreplacethetext"Fell"totheleftofthe
withthetext"Hello!":
InputConnectionic=getCurrentInputConnection();
ic.deleteSurroundingText(4,0);
ic.commitText("Hello",1);
ic.commitText("!",1);
Composingtextbeforecommitting
IfyourIMEdoestextpredictionorrequiresmultiplestepstocomposeaglyphor
word,youcanshowtheprogressinthetextfielduntiltheusercommitstheword,andthenyou
canreplacethepartialcompositionwiththecompletedtext.Youmaygivespecialtreatmentto
thetextbyaddinga"span"toitwhenyoupassittoInputConnection#setComposingText().
Thefollowingsnippetshowshowtoshowprogressinatextfield:
InputConnectionic=getCurrentInputConnection();
ic.setComposingText("Composi",1);
...
ic.setComposingText("Composin",1);
...
ic.commitText("Composing",1);
Thefollowingscreenshotsshowhowthisappearstotheuser:
Figure3.Composingtextbeforecommitting.
Interceptinghardwarekeyevents
Eventhoughtheinputmethodwindowdoesn'thaveexplicitfocus,itreceiveshardwarekey
eventsfirstandcanchoosetoconsumethemorforwardthemalongtotheapplication.For
example,youmaywanttoconsumethedirectionalkeystonavigatewithinyourUIforcandidate
selectionduringcomposition.Youmayalsowanttotrapthebackkeytodismissanypopups
originatingfromtheinputmethodwindow.
Tointercepthardwarekeys,override
onKeyDown()
andonKeyUp().
SeetheSoftKeyboardsample
appforanexample.
Remembertocallthesuper()methodforkeysyoudon'twanttohandleyourself.
CreatinganIMESubtype
SubtypesallowtheIMEtoexposemultipleinputmodesandlanguagessupportedbyanIME.A
subtypecanrepresent:
Alocalesuchasen_USorfr_FR
Aninputmodesuchasvoice,keyboard,orhandwriting
Otherinputstyles,forms,orpropertiesspecifictotheIME,suchas10-keyorqwerty
keyboardlayouts.
Basically,themodecanbeanytextsuchas"keyboard","voice",andsoforth.
Asubtypecanalsoexposeacombinationofthese.
SubtypeinformationisusedforanIMEswitcherdialogthat'savailablefromthenotification
barandalsoforIMEsettings.Theinformationalsoallowstheframeworktobringupa
specificsubtypeofanIMEdirectly.WhenyoubuildanIME,usethesubtypefacility,because
ithelpstheuseridentifyandswitchbetweendifferentIMElanguagesandmodes.
Youdefinesubtypesinoneoftheinputmethod'sXMLresourcefiles,usingthe
element.ThefollowingsnippetdefinesanIMEwithtwo
subtypes:akeyboardsubtypefortheUSEnglishlocale,andanotherkeyboardsubtypeforthe
FrenchlanguagelocaleforFrance:
/>
ToensurethatyoursubtypesarelabeledcorrectlyintheUI,use%stogetasubtypelabel
thatisthesameasthesubtype’slocalelabel.Thisisdemonstratedinthenexttwosnippets.
Thefirstsnippetshowspartoftheinputmethod'sXMLfile:
ThenextsnippetispartoftheIME'sstrings.xmlfile.Thestring
resourcelabel_subtype_generic,whichisusedbytheinputmethodUIdefinitionto
setthesubtype'slabel,isdefinedas:
%s
Thissetsthesubtype’sdisplaynameto“English(UnitedStates)”inanyEnglishlanguage
locale,ortotheappropriatelocalizationinotherlocales.
ChoosingIMEsubtypesfromthenotificationbar
TheAndroidsystemmanagesallsubtypesexposedbyallIMEs.IMEsubtypesare
treatedasmodesoftheIMEtheybelongto.Inthenotificationbar,ausercanselectan
availablesubtypeforthecurrently-setIME,asshowninthefollowingscreenshot:
Figure4.ChoosinganIMEsubtypefromthenotificationbar.
Figure5.SettingsubtypepreferencesinSystemSettings.
ChoosingIMEsubtypesfromSystemSettings
Ausercancontrolhowsubtypesareusedinthe“Language&input”settingspanelinthe
SystemSettingsarea.IntheSoftKeyboardsample,thefile
InputMethodSettingsFragment.javacontainsanimplementationthat
facilitatesasubtypeenablerintheIMEsettings.PleaserefertotheSoftKeyboardsamplein
theAndroidSDKformoreinformationabouthowtosupportInputMethodSubtypesinyourIME.
Figure6.ChoosingalanguagefortheIME.
GeneralIMEConsiderations
Herearesomeotherthingstoconsiderasyou'reimplementingyourIME:
ProvideawayforuserstosetoptionsdirectlyfromtheIME'sUI.
BecausemultipleIMEsmaybeinstalledonthedevice,provideawayfortheusertoswitchtoa
differentIMEdirectlyfromtheinputmethodUI.
BringuptheIME'sUIquickly.Preloadorloadondemandanylargeresourcessothatusers
seetheIMEassoonastheytaponatextfield.Cacheresourcesandviewsforsubsequent
invocationsoftheinputmethod.
Conversely,youshouldreleaselargememoryallocationssoonaftertheinputmethodwindowis
hidden,sothatapplicationscanhavesufficientmemorytorun.Considerusingadelayedmessage
toreleaseresourcesiftheIMEisinahiddenstateforafewseconds.
Makesurethatuserscanenterasmanycharactersaspossibleforthelanguageorlocale
associatedwiththeIME.Rememberthatusersmayusepunctuationinpasswordsoruser
names,soyourIMEhastoprovidemanydifferentcharacterstoallowuserstoentera
passwordandgetaccesstothedevice.
Previous
Next
Exceptasnoted,thiscontentis
licensedunder
CreativeCommonsAttribution2.5.Fordetailsand
restrictions,seetheContent
License.
AboutAndroid |
Legal |
Support