Working with the EditText | CodePath Android Cliffnotes

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

Check out the official text fields guide for even more input field details. ... You can type appNS as a shortcut in Android Studio to be declared. JumptoSectionTableofContentsOverviewUsageRetrievingtheValueCustomizingtheInputTypeFurtherEntryCustomizationAdjustingColorsDisplayingPlaceholderHintsChangingthebottomlinecolorListeningforEditTextInputDisplayingFloatingLabelFeedbackAddingCharacterCountingAddingPasswordVisibilityTogglesStylingTextInputLayoutProvidingAuto-completeReferencesWorkingwiththeEditTextEditPagePageHistoryOverview TheEditTextisthestandardtextentrywidgetinAndroidapps.Iftheuserneedstoentertextintoanapp,thisistheprimarywayforthemtodothat. TherearemanyimportantpropertiesthatcanbesettocustomizethebehaviorofanEditText.Severalofthesearelistedbelow.Checkouttheofficialtextfieldsguideforevenmoreinputfielddetails. Usage AnEditTextisaddedtoalayoutwithalldefaultbehaviorswiththefollowingXML: NotethatanEditTextissimplyathinextensionoftheTextViewandinheritsallofthesameproperties. RetrievingtheValue GettingthevalueofthetextenteredintoanEditTextisasfollows: EditTextsimpleEditText=(EditText)findViewById(R.id.et_simple); StringstrValue=simpleEditText.getText().toString(); CustomizingtheInputType Bydefault,anytextcontentswithinanEditTextcontrolisdisplayedasplaintext.BysettinginputType,wecanfacilitateinputofdifferenttypesofinformation,likephonenumbersandpasswords: Mostcommoninputtypesinclude: Type Description textUri TextthatwillbeusedasaURI textEmailAddress Textthatwillbeusedasane-mailaddress textPersonName Textthatisthenameofaperson textPassword Textthatisapasswordthatshouldbeobscured textVisiblePassword Text,nextbutton,andnomicrophoneinput number Anumericonlyfield phone Forenteringaphonenumber date Forenteringadate time Forenteringatime textMultiLine Allowmultiplelinesoftextinthefield YoucansetmultipleinputTypeattributesifneeded(separatedby'|') Youcanseealistofallavailableinputtypeshere. FurtherEntryCustomization Wemightwanttolimittheentrytoasingle-lineoftext(avoidnewlines): Youcanlimitthecharactersthatcanbeenteredintoafieldusingthedigitsattribute: Thiswouldrestrictthedigitsenteredtojust"0"and"1".Wemightwanttolimitthetotalnumberofcharacterswith: Usingthesepropertieswecandefinetheexpectedinputbehaviorfortextfields. AdjustingColors YoucanadjustthehighlightbackgroundcolorofselectedtextwithinanEditTextwiththeandroid:textColorHighlightproperty: witharesultsuchasthis: DisplayingPlaceholderHints YoumaywanttosetthehintfortheEditTextcontroltopromptauserforspecificinputwith: whichresultsin: Changingthebottomlinecolor AssumingyouareusingtheAppCompatlibrary,youcanoverridethestylescolorControlNormal,colorControlActivated,andcolorControlHighlight: #d32f2f #ff5722 #f44336 IfyoudonotseethesestylesappliedwithinaDialogFragment,thereisaknownbugwhenusingtheLayoutInflaterpassedintotheonCreateView()method. TheissuehasalreadybeenfixedintheAppCompatv23library.Seethisguideabouthowtoupgrade.AnothertemporaryworkaroundistousetheActivity'slayoutinflaterinsteadoftheonepassedintotheonCreateView()method: publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState){ Viewview=getActivity().getLayoutInflater().inflate(R.layout.dialog_fragment,container); } ListeningforEditTextInput CheckoutthebasiceventlistenerscliffnotesforalookathowtolistenforchangestoanEditTextandperformanactionwhenthosechangesoccur. DisplayingFloatingLabelFeedback Traditionally,theEditTexthidesthehintmessage(explainedabove)aftertheuserstartstyping.Inaddition,anyvalidationerrormessageshadtobemanagedmanuallybythedeveloper. StartingwithAndroidMandthedesignsupportlibrary,theTextInputLayoutcanbeusedtosetupafloatinglabeltodisplayhintsanderrormessages.First,wraptheEditTextinaTextInputLayout: NowthehintwillautomaticallybegintofloatoncetheEditTexttakesfocusasshownbelow: WecanalsousetheTextInputLayouttodisplayerrormessagesusingthesetErrorandsetErrorEnabledpropertiesintheactivityatruntime: privatevoidsetupFloatingLabelError(){ finalTextInputLayoutfloatingUsernameLabel=(TextInputLayout)findViewById(R.id.username_text_input_layout); floatingUsernameLabel.getEditText().addTextChangedListener(newTextWatcher(){ //... @Override publicvoidonTextChanged(CharSequencetext,intstart,intcount,intafter){ if(text.length()>0&&text.length()<=4){ floatingUsernameLabel.setError(getString(R.string.username_required)); floatingUsernameLabel.setErrorEnabled(true); }else{ floatingUsernameLabel.setErrorEnabled(false); } } @Override publicvoidbeforeTextChanged(CharSequences,intstart,intcount, intafter){ //TODOAuto-generatedmethodstub } @Override publicvoidafterTextChanged(Editables){ } }); } HereweusetheaddTextChangedListenertowatchasthevaluechangestodeterminewhentodisplaytheerrormessageorreverttothehint. AddingCharacterCounting TextInputLayoutcanexposeacharactercounterforanEditTextdefinedwithinit.ThecounterwillberenderedbelowtheEditTextandcanchangecolorsofboththelineandcharactercounterifthemaximumnumberofcharactershasbeenexceeded: TheTextInputLayoutsimplyneedstodefineapp:counterEnabledandapp:CounterMaxLengthintheXMLattributes.ThesesettingscanalsobedefineddynamicallythroughsetCounterEnabled()andsetCounterMaxLength(): AddingPasswordVisibilityToggles IfyouuseanEditTextwithaninputpasswordtype,youcanalsoenableaniconthatcanshoworhidetheentiretextusingthepasswordToggleEnabledattribute.YoucanalsochangethedefaulteyeiconwithpasswordToggleDrawableattributeorthecolorhintusingthepasswordToggleTintattribute.SeetheTextInputLayoutattributesformoredetails. StylingTextInputLayout Makesureyouhavetheappnamespace(xmlns:app="http://schemas.android.com/apk/res-auto"definedinyourouterlayout.YoucantypeappNSasashortcutinAndroidStudiotobedeclared. Thehinttextcanbestyledbydefiningapp:hintTextAppearance,andtheerrortextcanbechangedwithapp:errorTextAppearance.Thecountertextandoverflowtextcanalsohavetheirowntextstylesbydefiningapp:counterTextAppearanceandapp:counterOverflowTextAppearance.WecanusetextColor,textSize,andfontFamilytohelpchangethecolor,size,orfont(placeinsidestyles.xml): #aa5353cc #ff0000 ProvidingAuto-complete Checkouttheofficialtextfieldsguideforastep-by-steponhowtosetupautocompletefortheentry. References http://developer.android.com/guide/topics/ui/controls/text.html http://code.tutsplus.com/tutorials/android-user-interface-design-edittext-controls--mobile-7183 http://www.codeofaninja.com/2012/01/android-edittext-example.html http://www.tutorialspoint.com/android/android_edittext_control.htm http://developer.android.com/reference/android/widget/EditText.html http://android-developers.blogspot.com/2015/10/android-support-library-231.html?linkId=17977963



請為這篇文章評分?