Onscreen Input Methods | Android Developers - Huihoo

文章推薦指數: 80 %
投票人數:10人

Starting from Android 1.5, the Android platform offers an Input Method Framework (IMF) that lets you create on-screen input methods such as software ... Home Startseite ホーム 主页 首頁 SDK DevGuide Handbuch Guía Guide Guida 開発ガイド 开发人员指南 開發指南 Reference Referenz Referencia Référence Riferimento リファレンス 参考 參考資料 Resources Videos ビデオ Blog ブログ 博客 網誌 Android.com   TechnicalResources SampleCode Beispielcode Códigodeejemplo Exempledecode Codicediesempio サンプルコード GettingtheSamples Articles Tutorials Lernprogramme Tutoriales Didacticiels Esercitazioni チュートリアル Topics Community Comunidad Communauté コミュニティ 社区 社群 DeveloperForums IRC,Twitter More CommonTasks TroubleshootingTips FAQs AppFrameworkFAQ LicensingFAQ SecurityFAQ Articles> OnscreenInputMethods Seealso CreatinganInput Method SoftKeyboardsample StartingfromAndroid1.5,theAndroidplatformoffersanInputMethod Framework(IMF)thatletsyoucreateon-screeninputmethodssuchassoftware keyboards.ThisarticleprovideanoverviewofwhatAndroidinputmethodeditors (IMEs)areandwhatanapplicationneedstodotoworkwellwiththem.TheIMF isdesignedtosupportnewclassesofAndroiddevices,suchasthosewithout hardwarekeyboards,soitisimportantthatyourapplicationworkswellwiththe IMFandoffersagreatexperienceforusers. Whatisaninputmethod? TheAndroidIMFisdesignedtosupportavarietyofIMEs,includingsoft keyboard,hand-writingrecognizers,andhardkeyboardtranslators.Ourfocus, however,willbeonsoftkeyboards,sincethisisthekindofinputmethodthat iscurrentlypartoftheplatform. AuserwillusuallyaccessthecurrentIMEbytappingonatextviewto edit,asshownhereinthehomescreen: Thesoftkeyboardispositionedatthebottomofthescreenoverthe application'swindow.Toorganizetheavailablespacebetweentheapplication andIME,weuseafewapproaches;theoneshownhereiscalledpanand scan,andsimplyinvolvesscrollingtheapplicationwindowaroundsothat thecurrentlyfocusedviewisvisible.Thisisthedefaultmode,sinceitisthe safestforexistingapplications. Mostoftenthepreferredscreenlayoutisaresize,wherethe application'swindowisresizedtobeentirelyvisible.Anexampleisshown here,whencomposingane-mailmessage: Thesizeoftheapplicationwindowischangedsothatnoneofitishiddenby theIME,allowingfullaccesstoboththeapplicationandIME.Thisofcourse onlyworksforapplicationsthathavearesizeableareathatcanbereducedto makeenoughspace,buttheverticalspaceinthismodeisactuallynolessthan whatisavailableinlandscapeorientation,soveryoftenanapplicationcan alreadyaccommodateit. Thefinalmajormodeisfullscreenorextract mode.ThisisusedwhentheIMEistoolargetoreasonablysharespace withtheunderlyingapplication.WiththestandardIMEs,youwillonly encounterthissituationwhenthescreenisinalandscapeorientation, althoughotherIMEsarefreetouseitwhenevertheydesire.Inthis casetheapplicationwindowisleftas-is,andtheIMEsimplydisplays fullscreenontopofit,asshownhere: BecausetheIMEiscoveringtheapplication,ithasitsowneditingarea, whichshowsthetextactuallycontainedintheapplication.Therearealsosome limitedopportunitiestheapplicationhastocustomizepartsoftheIME(the "done"buttonatthetopandenterkeylabelatthebottom)toimprovetheuser experience. BasicXMLattributesforcontrollingIMEs Thereareanumberofthingsthesystemdoestotrytohelpexisting applicationsworkwithIMEsaswellaspossible,suchas: Usepanandscanmodebydefault,unlessitcanreasonablyguessthat resizemodewillworkbytheexistenceoflists,scrollviews,etc. AnalyzethevariousexistingTextViewattributestoguessatthekindof content(numbers,plaintext,etc)tohelpthesoftkeyboarddisplayan appropriatekeylayout. AssignafewdefaultactionstothefullscreenIME,suchas"nextfield" and"done". Therearealsosomesimplethingsyoucandoinyourapplicationthatwill oftengreatlyimproveitsuserexperience.Exceptwhereexplicitlymentioned, thesewillworkinanyAndroidplatformversion,eventhoseprevioustoAndroid 1.5(sincetheywillsimplyignorethesenewoptions). SpecifyingeachEditTextcontrol'sinputtype Themostimportantthingforanapplicationtodoistousethenew android:inputType attributeoneachEditText.Theattributeprovidesmuchricher information aboutthetextcontent.Thisattributeactuallyreplacesmanyexisting attributes(android:password, android:singleLine, android:numeric, android:phoneNumber, android:capitalize, android:autoText,and android:editable).Ifyouspecifytheolderattributes andthenewandroid:inputTypeattribute,thesystemuses android:inputTypeandignorestheothers. Theandroid:inputTypeattributehasthreepieces: Theclassistheoverallinterpretationofcharacters.The currentlysupportedclassesaretext(plaintext), number(decimalnumber),phone(phonenumber),and datetime(adateortime). Thevariationisafurtherrefinementontheclass.Inthe attributeyouwillnormallyspecifytheclassandvarianttogether,withthe classasaprefix.Forexample,textEmailAddressisatextfield wheretheuserwillentersomethingthatisane-mailaddress([email protected])so thekeylayoutwillhavean'@'characterineasyaccess,and numberSignedisanumericfieldwithasign.Ifonlytheclassis specified,thenyougetthedefault/genericvariant. Additionalflagscanbespecifiedthatsupplyfurtherrefinement. Theseflagsarespecifictoaclass.Forexample,someflagsforthe textclassaretextCapSentences, textAutoCorrect,andtextMultiline. Asanexample,hereisthenewEditTextfortheIMapplication'smessagetextview: Afulldescriptionofalloftheinputtypescanbefoundinthe documentation.Itisimportanttomakeuseofthecorrectinputtypesthatare available,sothatthesoftkeyboardcanusetheoptimalkeyboardlayoutforthe texttheuserwillbeentering. Enablingresizemodeandotherwindowfeatures Thesecondmostimportantthingforyourapptodoistospecifytheoverall behaviorofyourwindowinrelationtotheinputmethod.Themostvisibleaspect ofthisiscontrollingresizevs.panandscanmode,butthereareotherthings youcandoaswelltoimproveyouruserexperience. Youwillusuallycontrolthisbehaviorthroughthe android:windowSoftInputModeattributeoneach definitioninyour AndroidManifest.xml.Liketheinputtype,thereareacouple differentpiecesofdatathatcanbespecifiedherebycombiningthem together: Thewindowadjustmentmodeisspecifiedwitheither adjustResizeoradjustPan.Itishighlyrecommended thatyoualwaysspecifyoneortheother. YoucanfurthercontrolwhethertheIMEwillbeshownautomaticallywhen youractivityisdisplayedandothersituationswheretheusermovestoit.The systemwon'tautomaticallyshowanIMEbydefault,butinsomecasesitcanbe convenientfortheuserifanapplicationenablesthisbehavior.Youcanrequest thiswithstateVisible.Therearealsoanumberofotherstate optionsforfiner-grainedcontrolthatyoucanfindinthedocumentation. Atypicalexampleofthisfieldcanbeseeintheeditcontactactivity, whichensuresitisresizedandautomaticallydisplaystheIMEfortheuser: ... Note:StartingfromAndroid1.5(APILevel3), theplatformoffersanewmethod, setSoftInputMode(int), thatnon-Activitywindowscanusetocontroltheirbehavior.Callingthismethod inyourwillmakeyourapplicationincompatiblewithpreviousversionsofthe Androidplatform. Controllingtheactionbuttons Thefinalcustomizationwewilllookatisthe"action"buttonsintheIME. Therearecurrentlytwotypesofactions: Theenterkeyonasoftkeyboardistypicallyboundtoanactionwhennot operatingonamult-lineedittext.Forexample,ontheG1pressingthehard enterkeywilltypicallymovetothenextfieldortheapplicationwill interceptittoexecuteanaction;withasoftkeyboard,thisoverloadingofthe enterkeyremains,sincetheenterbuttonjustsendsanenterkeyevent. Wheninfullscreenmode,anIMEmayalsoputanadditionalactionbuttonto therightofthetextbeingedited,givingtheuserquickaccesstoacommon applicationoperation. Theseoptionsarecontrolledwiththeandroid:imeOptions attributeonTextView.Thevalueyousupplyherecanbeany combinationof: Oneofthepre-definedactionconstants(actionGo, actionSearch,actionSend,actionNext, actionDone).Ifnoneofthesearespecified,thesystemwillinfer eitheractionNextoractionDonedependingonwhether thereisafocusablefieldafterthisone;youcanexplicitlyforcenoaction withactionNone. TheflagNoEnterActionoptiontellstheIMEthattheaction shouldnotbeavailableontheenterkey,evenifthetextitselfis notmulti-line.Thisavoidshavingunrecoverableactionslike(send)thatcanbe accidentallytouchedbytheuserwhiletyping. TheflagNoAccessoryActionremovestheactionbuttonfromthe textarea,leavingmoreroomfortext.TheflagNoExtractUi completelyremovesthetextarea,allowingtheapplicationtobeseenbehind it. ThepreviousIMapplicationmessageviewalsoprovidesanexampleofan interestinguseofimeOptions,tospecifythesendactionbutnot letitbeshownontheenterkey: android:imeOptions="actionSend|flagNoEnterAction" APIsforcontrollingIMEs FormoreadvancedcontrolovertheIME,thereareavarietyofnewAPIsyou canuse.Unlessspecialcareistaken(suchasbyusingreflection),usingthese APIswillcauseyourapplicationtobeincompatiblewithpreviousversionsof Android,andyoushouldmakesureyouspecify android:minSdkVersion="3"inyourmanifest.Formoreinformation, seethedocumentationforthemanifestelement. TheprimaryAPIisthenewandroid.view.inputmethod.InputMethodManagerclass,whichyoucanretrievewithContext.getSystemService(). Itallowsyoutointeractwiththeglobalinputmethodstate,suchas explicitlyhidingorshowingthecurrentIME'sinputarea. Therearealsonewwindowflagscontrollinginputmethodinteraction,whichyoucancontrolthroughtheexistingWindow.addFlags()methodandnewWindow.setSoftInputMode()method.ThePopupWindow classhasgrowncorrespondingmethodstocontroltheseoptionsonits window.OnethinginparticulartobeawareofisthenewWindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IMconstant,whichisusedtocontrolwhetherawindowisontopoforbehindthecurrentIME. MostoftheinteractionbetweenanactiveIMEandapplicationisdonethroughtheandroid.view.inputmethod.InputConnection class.ThisistheAPIanapplicationimplement,whichanIMEcallsto performtheappropriateeditoperationsontheapplication.Youwon't normallyneedtoworryaboutthis,sinceTextViewprovidesitsownimplementationforitself. TherearealsoahandfulofnewViewAPIs,themostimportantofthesebeingonCreateInputConnection()whichcreatesanewInputConnectionforanIME(andfillsinanandroid.view.inputmethod.EditorInfo structurewithyourinputtype,IMEoptions,andotherdata);again, mostdeveloperswon'tneedtoworryaboutthis,sinceTextViewtakes careofitforyou. ↑Gototop ←BacktoArticles Exceptasnoted,thiscontentis licensedunder CreativeCommonsAttribution2.5.Fordetailsand restrictions,seetheContent License. SiteTermsofService- PrivacyPolicy- BrandGuidelines



請為這篇文章評分?