How to Handle IME Options on Action Button Click in Android?

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

How to Handle IME Options on Action Button Click in Android? Last Updated : 19 Oct, 2021. We often observe that a keyboard pops up when we try to enter ... Skiptocontent TutorialsPracticeDS&Algo.DSATopic-wiseDSACompany-wiseAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesISROCSISROCSSolvedPapersISROCSOriginalPapersandOfficialKeysISROCSSyllabusforScientist/EngineerExamUGCNETCSUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsGeekontheTopCareersInternshipJobsApplyforJobsPostaJobCourses ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantri HomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningWebDevelopmentPuzzlesProjectIdeasSchoolLearning RelatedArticles ▲RelatedArticlesBottomNavigationBarinAndroidHowtoChangetheBackgroundColorofButtoninAndroidusingColorStateList?AndroidTutorialAndroidArchitectureServicesinAndroidwithExampleMVVM(ModelViewViewModel)ArchitecturePatterninAndroidHowtoAddandCustomizeBackButtonofActionBarinAndroid?AndroidProjects-FromBasictoAdvancedLevelHowtochangethecolorofActionBarinanAndroidApp?HowtoInstallandSetupAndroidStudioonWindows?ContentProvidersinAndroidwithExampleKotlinAndroidTutorialCardViewinAndroidWithExampleHowtoPushNotificationinAndroidusingFirebaseCloudMessaging?HowtoChangetheColorofStatusBarinanAndroidApp?ImageSliderinAndroidusingViewPagerHowtoCreateaQuizAppInAndroid?HowtoUpdateGradleinAndroidStudio?AndroidProjectfolderStructureAndroid|build.gradleBroadcastReceiverinAndroidWithExampleFix"UnabletolocateadbwithinSDK"inAndroidStudioHowtoUploadProjectonGitHubfromAndroidStudio?BestWaytoBecomeAndroidDeveloper–ACompleteRoadmapFirebaseAuthenticationwithPhoneNumberOTPinAndroidHowtoFix“FailedtoinstallthefollowingAndroidSDKpackagesassomelicenseshavenotbeenaccepted”ErrorinAndroidStudio?AssetsFolderinAndroidStudioExternalStorageinAndroidwithExampleHowtoAddaFloatingActionButtontoBottomNavigationBarinAndroid?NavigationDrawerinAndroidTableofContentsBottomNavigationBarinAndroidHowtoChangetheBackgroundColorofButtoninAndroidusingColorStateList?AndroidTutorialAndroidArchitectureServicesinAndroidwithExampleMVVM(ModelViewViewModel)ArchitecturePatterninAndroidHowtoAddandCustomizeBackButtonofActionBarinAndroid?AndroidProjects-FromBasictoAdvancedLevelHowtochangethecolorofActionBarinanAndroidApp?HowtoInstallandSetupAndroidStudioonWindows?ContentProvidersinAndroidwithExampleKotlinAndroidTutorialCardViewinAndroidWithExampleHowtoPushNotificationinAndroidusingFirebaseCloudMessaging?HowtoChangetheColorofStatusBarinanAndroidApp?ImageSliderinAndroidusingViewPagerHowtoCreateaQuizAppInAndroid?HowtoUpdateGradleinAndroidStudio?AndroidProjectfolderStructureAndroid|build.gradleBroadcastReceiverinAndroidWithExampleFix"UnabletolocateadbwithinSDK"inAndroidStudioHowtoUploadProjectonGitHubfromAndroidStudio?BestWaytoBecomeAndroidDeveloper–ACompleteRoadmapFirebaseAuthenticationwithPhoneNumberOTPinAndroidHowtoFix“FailedtoinstallthefollowingAndroidSDKpackagesassomelicenseshavenotbeenaccepted”ErrorinAndroidStudio?AssetsFolderinAndroidStudioExternalStorageinAndroidwithExampleHowtoAddaFloatingActionButtontoBottomNavigationBarinAndroid?NavigationDrawerinAndroidImproveArticle SaveArticle LikeArticle HowtoHandleIMEOptionsonActionButtonClickinAndroid?LastUpdated: 19Oct,2021Weoftenobservethatakeyboardpopsupwhenwetrytoenterinputineditablefields.Theseinputsaregenerallyacceptedbytheapplicationforperformingspecificfunctionsanddisplaydesiredresults.Oneofthemostcommoneditablefields,thatwecanseeinmostoftheapplicationsindailyuseistheSearchBar.YouTubesearchqueryresultsWhenthekeyboardisinvoked,youseeabuttonwithamagnifiericonatthebottom.Thisletstheuserassumethatclickingthisbuttonwouldhelpthemsearchtheirquery.However,thedevelopersofthisapplicationhaveexplicitlysetthemagnifiericon,whichbydefaultcouldbesomethingelse.ThiscanbedonebyexplicitlyspecifyingthetypeoficonrequiredusingtheIMEOptions.Tolearnaboutthelistofavailableiconsandhowtochangethem,refertothebelowarticle.InvokingSearchButtoninKeyboardWhileTypinginEditTextinAndroid.Inthisarticle,wewillshowyouhowtohandletheon-clickeventsonthesebuttons.Wantamorefast-paced&competitiveenvironmenttolearnthefundamentalsofAndroid?Clickheretoheadtoaguideuniquelycuratedbyourexpertswiththeaimtomakeyouindustryreadyinnotime!StepbyStepImplementationStep1:CreateaNewProjectTocreateanewprojectinAndroidStudiopleaserefertoHowtoCreate/StartaNewProjectinAndroidStudio.WedemonstratedtheapplicationinKotlin,somakesureyouselectKotlinastheprimarylanguagewhilecreatingaNewProject.Step2:Workingwiththeactivity_main.xmlfileNavigatetotheapp>res>layout>activity_main.xmlandaddthebelowcodetothatfile.Belowisthecodefortheactivity_main.xmlfile. XML        Step3:WorkingwiththeMainActivity.ktfileGototheMainActivity.ktfileandrefertothefollowingcode.BelowisthecodefortheMainActivity.ktfile.Commentsareaddedinsidethecodetounderstandthecodeinmoredetail.Kotlinimportandroidx.appcompat.app.AppCompatActivityimportandroid.os.Bundleimportandroid.view.inputmethod.EditorInfoimportandroid.widget.EditTextimportandroid.widget.TextViewimportandroid.widget.Toast  classMainActivity:AppCompatActivity(){    overridefunonCreate(savedInstanceState:Bundle?){        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          //DeclaringtheEditTextfromthelayoutfile        valmyEditText=findViewById(R.id.et1)                  //CallingthedoSomethingfunction        doSomething(myEditText)    }            privatefundoSomething(search:EditText){        search.setOnEditorActionListener(TextView.OnEditorActionListener{_,actionId,_->                        if(actionId==EditorInfo.IME_ACTION_DONE){                                  //Dosomethingofyourinterest.                //WeinthisexamplescreatedthefollowingToasts                if(search.text.toString()=="geeksforgeeks"){                    Toast.makeText(applicationContext,"WelcometoGFG",Toast.LENGTH_SHORT).show()                }else{                    Toast.makeText(applicationContext,"InvalidInput",Toast.LENGTH_SHORT).show()                }                  return@OnEditorActionListenertrue            }            false        })    }}Sobasically,inthefunctiondoSomething,youcanobserveIME_ACTION_DONEintheouterifcondition.ThisisbecausewhenweinvokedthekeyboardbypressingontheEditText,wesawtheDonebutton.ThisiswhennoIMEOptionsissetinattributesoftheEditTextintheLayoutorisadefaultcondition.Butifyousetittosearch,go,etc,thenyoumayliketoreferbelowtomaketheapplicationwork.Replacewith:EditorInfo.IME_ACTION_DONE=WhennoIMEoptionsisspecified(default)EditorInfo.IME_ACTION_SEARCH=WhenIMEoptionsisactionSearchEditorInfo.IME_ACTION_GO=WhenIMEoptionsisactionGoEditorInfo.IME_ACTION_NEXT=WhenIMEoptionsisactionNextEditorInfo.IME_ACTION_PREVIOUS=WhenIMEoptionsisactionPreviousEditorInfo.IME_ACTION_SEND=WhenIMEoptionsisactionSendInput:ClickonEditTextandtypesomething.NowpresstheDonebuttonatthebottomandobserveifaToastappears.Similarly,typein“geeksforgeeks”andobservetheToast.Output:YoucanseethatweobservedifferentToastsfordifferentinputs.Thisshowsthatourfunctioncorrectlyrespondstothekeyboardactionbutton(Donebutton)intheformofToasts.https://media.geeksforgeeks.org/wp-content/uploads/20210722195255/22222.mp4MyPersonalNotes arrow_drop_upSave LikePreviousWhatisAndroidActivity"launchMode"?Next fromtimestamp()FunctionOfDatetime.dateClassInPythonRecommendedArticlesPage:15,Dec2025,Jun2021,Sep2023,Sep2023,Sep2028,Oct2009,Dec2021,Dec2002,Feb2103,May2125,Sep2124,Feb2121,Apr2117,Jan2011,Oct2022,Mar2121,May2106,Sep2109,Feb2109,Aug2114,Dec2027,Oct1931,Jul2009,Oct20ArticleContributedBy:aashaypawar@aashaypawarVotefordifficultyEasy Normal Medium Hard ExpertImprovedBy:rs1686740ArticleTags:AndroidKotlinPracticeTags:AndroidReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinAndroidHowtoCreateandAddDatatoSQLiteDatabaseinAndroid?AndroidRecyclerViewinKotlinHowtoViewandLocateSQLiteDatabaseinAndroidStudio?HowtoRetrieveDatafromtheFirebaseRealtimeDatabaseinAndroid?HowtoConvertKotlinCodetoJavaCodeinAndroidStudio?MostvisitedinKotlinAndroidRecyclerViewinKotlinKotlinArrayAndroidUILayoutsHowtoConvertKotlinCodetoJavaCodeinAndroidStudio?MVP(ModelViewPresenter)ArchitecturePatterninAndroidwithExample× Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt!



請為這篇文章評分?