The Soft Keyboard on Android | PSPDFKit

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

The soft keyboard (also called the onscreen keyboard) is the main input method on Android devices, and almost every Android developer needs to work with ... PSPDFKit Products Solutions Aviation StreamlineYourFlightReleases Construction DigitizePDFFormsandDrawings Education MoveYourApptotheHeadoftheClass Legal HandleandReviewDocumentsinRealTime Government ServePublicRecordsSecurelyandIntuitively Documentation Blog ExploretheBlog BlogOverview Development Releases Tutorials CustomerStories Solutions CompanyNews Archive FeaturedArticles MigratingOurWebCodebasefromFlowtoTypeScript HowtoDigitallySignaPDFUsingaYubiKey UsingInstantLayersforOnsiteVisits Pricing FreeTrial ContactSales ContactSales ContactSales T PSPDFKit Products Solutions Documentation Blog Pricing Company CustomerPortal TechnicalSupport FreeTrial ContactSales Web PDFSDK Viewing Viewer FormViewing Markup Annotations ElectronicSignatures DigitalSignatures DocumentEditor FormFilling Collaboration Instant InstantComments AdvancedTools FormDesigner Redaction Comparison OCR PDFGeneration FileTypes OfficeFiles ImageDocuments SupportFor Web Electron Mobile PDFSDK Viewing Viewer IndexedSearch FormViewing ReaderView Markup Annotations ElectronicSignatures DigitalSignatures DocumentEditor FormFilling Collaboration Instant InstantComments Replies AdvancedTools Redaction Comparison OCR FileTypes OfficeFiles ImageDocuments SupportFor iOS Android ReactN. Flutter Server ProcessorforLinux Editing XFDF OCR Redaction PDFGeneration OfficeFiles ImageDocuments Libraryfor.NET Viewer DocumentEditor FormFilling Redaction OCR LibraryforJava Viewer DocumentEditor FormFilling Redaction OCR API PDFAPI PDFGenerator Watermark OCR ConverterAPI ImagetoPDF OfficetoPDF HTMLtoPDF PDFtoImage HTMLtoImage OfficetoImage EditorAPI Merge Split Delete Flatten Duplicate FeaturesList Aviation Construction Education Legal Government Web Web Overview CodeSamples GetStarted APIReference Guides LaunchDemo Frameworks VanillaJavaScript Blazor React Electron Angular Next.js Vue RubyonRails Svelte TypeScript PWA Mobile iOS Overview CodeSamples GetStarted APIReference Guides Android Overview CodeSamples GetStarted APIReference Guides HybridTechnologies Flutter Xamarin.Android Electron Ionic ReactNative Cordova Xamarin.iOS Server ProcessorforLinux Overview GetStarted APIReference Guides Libraryfor.NET Overview ExampleProject GetStarted APIReference Guides LibraryforJava Overview ExampleProject GetStarted APIReference Guides Desktop UWP Overview ExampleProjects GetStarted APIReference Guides MacCatalyst Overview ExampleProjects GetStarted APIReference Guides HybridTechnologies Electron ReactNative APITools PDFAPITools ToolsOverview GetStarted Guides PDFGenerator Watermark OCR ImagetoPDF OfficetoPDF HTMLtoPDF PDFtoImage HTMLtoImage OfficetoImage Merge Split Delete Flatten Duplicate Overview TechnicalSupport CustomerPortal BlogOverview Development Releases Tutorials CustomerStories Solutions CompanyNews Archive About Team Careers We’reHiring! Contactus Newsletter Legal Thesoftkeyboard(alsocalledtheonscreenkeyboard)isthemaininputmethodonAndroiddevices,andalmosteveryAndroiddeveloperneedstoworkwiththiscomponentatsomepoint.Atfirstglance,itmayseemlikeatrivialtask,sincetheonlyoperationsyouusuallywantareforshowingandhidingthekeyboard—actionsthatcanhappenautomaticallythroughtheavailableAndroidAPIs.Butthere’sabitmoretothesoftkeyboardthanmeetstheeye,solet’stakealookatofferedAPIsandtrytounderstandwhataretheyusedfor. windowSoftInputModeinAndroidManifest ThewindowSoftInputModeattributeissetontheactivity—usuallythroughtheAndroidmanifest—anditspecifiesthewaytheonscreenkeyboardbehaveswhenanactivitycomesintoauser’sfocus.Wesuggestfirstcheckingouttheavailablecustomizationoptionstoseeiftheywillbeenoughforaparticularusecasebeforewritinganycustomkeyboardhandlinglogic. Usingthisattribute,it’spossibletoinfluencetwoaspects: Thevisibilityofthesoftkeyboardwhentheactivityreceivesthefocus(stateUnspecified,stateHidden,stateAlwaysVisible,etc.). Thechangesmadetotheactivity’smainwindowtoaccommodatethekeyboardview.Theoptionshereareresizing,whichwillmaketheactivitylayoutsmallinordertofreespaceforthekeyboard,orpanningtheactivity’scontentstomakethecurrentfocusviewvisibleandkeepthepartofthewindowunderthesoftkeyboard(adjustUnspecified,adjustResize,andadjustPan). TakealookattheofficialdocumentationforwindowSoftInputModeformoreinformation. Allthatsaid,ifwindowSoftInputModecustomizationoptionsaren’tsufficientforyourusecase,hereishowtomanuallycontrolthevisibilityofthesoftkeyboard. HowtoHidetheSoftKeyboard Becausehidingthekeyboardismorecomplexthanshowingit,andbecauseit’srequiredmoreoften,let’sstartwithit. TherequiredwayforanapplicationtohidethesoftkeyboardisbyusingInputMethodManager#hideSoftInputFromWindow.However,toaccessthisfunctionality,it’snecessarytoprovideacontextandawindowtoken.Gettingthecontextisusuallytrivial,butyoumaybewonderingwhatthewindowtokenisandwhatit’susedfor. Awindowtokenisaspecialtokenusedbythewindowmanagertouniquelyidentifyawindowinthesystem.Itisimportantforsecurityreasons;itmakesitimpossibletodrawontopofthewindowsofotherapplications,therebypreventingpotentialmaliciousintent. So,eventhoughourintentionistohidethekeyboard,westillmustprovideawindowtokenthatmatchesthewindowcurrentlyacceptinginput.Otherwise,InputMethodManagerwillrejecttherequest.Thissecuritymechanismpreventsoneapplicationfromforce-closingthekeyboardopenedbyanotherapplication. Nowthatweknowmoreaboutthewindowtoken,thenextquestionishowwegetit.Unfortunately,thereisnoonewaytorequestthewindowtokenonalldevicesandAPIs,butwe’llpresentafewthatshouldworkinmostcases. Hereishowtohidethesoftkeyboard: funhideKeyboard(view:View){ //Retrievingthetokeniftheviewishostedbythefragment. varwindowToken:IBinder?=view.windowToken //Retrievingthetokeniftheviewishostedbytheactivity. if(windowToken==null){ if(view.contextisActivity){ valactivity=view.contextasActivity if(activity.window!=null&&activity.window.decorView!=null){ windowToken=activity.window.decorView.windowToken } } } //Hideifshownbefore. valinputMethodManager=view .context .getSystemService(Context.INPUT_METHOD_SERVICE)asInputMethodManager inputMethodManager.hideSoftInputFromWindow(windowToken,0) }voidhideKeyboard(final@NonNullViewview){ //Retrievingthetokeniftheviewishostedbythefragment. IBinderwindowToken=view.getWindowToken(); //Retrievingthetokeniftheviewishostedbytheactivity. if(windowToken==null){ if(view.getContext()instanceofActivity){ finalActivityactivity=(Activity)view.getContext(); if(activity.getWindow()!=null&&activity.getWindow().getDecorView()!=null){ windowToken=activity.getWindow().getDecorView().getWindowToken(); } } } //Hideifshownbefore. InputMethodManagerinputMethodManager=(InputMethodManager)view .getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(windowToken,0); }HowtoShowtheSoftKeyboard Let’stakealookatasimpleAPIforshowingthesoftkeyboard.Todothis,thereisnolongeraneedtoprovideawindowtoken.However,thereisasmalltweakrequiredinordertomakesurethatthekeyboardiscorrectlyshowninlandscapemode: funshowKeyboard(view:View){ //Whenwewantthekeyboardtobedisplayedonphonesinlandscapemode,weneed //tospecifythe`SHOW_FORCED`flagtocorrectlyshowthefullscreenkeyboard. valisLandscape=view .context .resources .configuration .orientation==Configuration.ORIENTATION_LANDSCAPE valflags=if(isLandscape)SHOW_FORCEDelseSHOW_IMPLICIT valinputMethodManager=view .context .getSystemService(Context.INPUT_METHOD_SERVICE)asInputMethodManager inputMethodManager.showSoftInput(view,flags) }voidshowKeyboard(final@NonNullViewview){ //Whenwewantthekeyboardtobedisplayedonphonesinlandscapemode,weneed //tospecifythe`SHOW_FORCED`flagtocorrectlyshowthefullscreenkeyboard. finalbooleanisLandscape=view .getContext() .getResources() .getConfiguration() .orientation==Configuration.ORIENTATION_LANDSCAPE; intflags=isLandscape?SHOW_FORCED:SHOW_IMPLICIT; InputMethodManagerinputMethodManager=(InputMethodManager)view .getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.showSoftInput(view,flags); } Inthiscodesnippet,weusedtheSHOW_FORCEDflagforlandscapemodeinsteadoftheusualSHOW_IMPLICITflaginordertomakesurethekeyboardwillbecorrectlydisplayed.ThedocumentationfortheSHOW_IMPLICITflagstatesthatthisrequestisindeedimplicitandthesystemmightnotfavortherequestinsomecircumstances,withlandscapemodeappearingtobeoneofsuchcases. Conclusion Inthisblogpost,wediscussedwhatthesoftkeyboardisandthereasonwhyit’smorecomplicatedtohidethanitistoshow.Hopefullythishasgivenyouabetteroverviewofthesoftkeyboardandsomehelpfultipsforworkingwithit. SharePost Free60-DayTrial TryPSPDFKitinyourapptoday. FreeTrial RelatedArticles Exploremore RELEASES | Android•Products PSPDFKit8forAndroidAddsElectronicSignaturesandJetpackCompose DEVELOPMENT | Android•Development•JetpackCompose•UI IntroducingJetpackComposeSupport DEVELOPMENT | Android•Development•Git RefactoringGitBrancheswithInteractiveRebaseandAutosquashinAndroidStudio



請為這篇文章評分?