EditText Tutorial With Example In Android Studio: Input Field

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

EditText is used to provide an input or text field, especially in forms. Learn the concept and attributes in detail with example and code in Android Studio. Togglenavigation Course FREEResource Contact JAVAForAndroid AndroidStudio DesignAndroidUI AndroidMaterialDesign AndroidProgramming AndroidDatabase CreateAndroidApp LearnAndroidUI EditTextTutorialWithExampleInAndroidStudio:InputFieldInAndroid,EditTextisastandardentrywidgetinandroidapps.ItisanoverlayoverTextViewthatconfiguresitselftobeeditable.EditTextisasubclassofTextViewwithtexteditingoperations.WeoftenuseEditTextinourapplicationsinordertoprovideaninputortextfield,especiallyinforms.ThemostsimpleexampleofEditTextisLoginorSign-inform. TextFieldsinAndroidStudioarebasicallyEditText: ImportantNote:An EditText issimplyathinextensionofa TextView.AnEditTextinheritsallthepropertiesofaTextView. TableOfContents1EditTextCode:2AttributesofEditText:3ExampleI–EditTextinAndroidStudio4ExampleII–EditTextinAndroidStudio5TextInputLayout/FloatingLabelsInEditText: EditTextCode: WecancreateaEditText instancebydeclaringitinsidealayout(XMLfile)orbyinstantiatingitprogrammatically(i.e.inJavaClass). EditTextcodeinXML: Retrieving/GettingtheValueFromEditTextInJavaClass: BelowistheexamplecodeofEditTextinwhichweretrievethevaluefromaEditTextinJavaclass.Wehaveusedthiscodeintheexampleyouwillfindattheendofthispost. EditTextsimpleEditText=(EditText)findViewById(R.id.simpleEditText); StringeditTextValue=simpleEditText.getText().toString(); AttributesofEditText: Nowlet’s wediscussfewattributesthathelpsustoconfigureaEditTextinyourxml. 1.id:idisanattributeusedtouniquelyidentifyatextEditText.Belowistheexamplecodeinwhichwesettheidofaedittext. 2.gravity:Thegravityattributeisanoptionalattributewhichisusedtocontrolthealignmentofthetextlikeleft,right,center,top,bottom,center_vertical,center_horizontaletc. BelowistheexamplecodewithexplanationincludedinwhichwesettherightgravityfortextofaEditText. 3.text:textattributeisusedtosetthetextinaEditText.Wecansetthetextinxmlaswellasinthejavaclass. Belowistheexamplecodeinwhichwesetthetext“Username”inaedittext. SettingtextinEditTextInJavaclass: Belowistheexamplecodeinwhichwesetthetextina textviewprogrammaticallymeansinjavaclass. EditTexteditText=(EditText)findViewById(R.id.simpleEditText); editText.setText("Username");//setthetextinedittext 4.hint:hintisanattributeusedtosetthehinti.e.whatyouwantusertoenterinthisedittext.Wheneveruserstarttotypeinedittextthehintwillautomaticallydisappear. Belowistheexamplecodewithexplanationinwhichwesetthehintofaedittext. SettinghintinEditTextInJavaclass: Belowistheexamplecodeinwhichwesetthetextina textviewprogrammaticallymeansinjavaclass. EditTexteditText=(EditText)findViewById(R.id.simpleEditText); editText.setHint("EnterYourNameHere");//displaythehint 5.textColor:textColorattributeisusedtosetthetextcolorofatextedittext.Colorvalueisintheformof“#argb”,“#rgb”,“#rrggbb”,or“#aarrggbb”. Belowistheexamplecodewithexplanationincludedinwhichwesettheredcolorforthedisplayedtextofaedittext. SettingtextColorinEditTextInJavaclass: Belowistheexamplecodeinwhichwesetthetextcolorofaedittextprogrammaticallymeansinjavaclass. EditTextsimpleEditText=(EditText)findViewById(R.id.simpleEditText); simpleEditText.setTextColor(Color.RED);//settheredtextcolor 6.textColorHint:textColorHintisanattributeusedtosetthecolorofdisplayedhint. Belowistheexamplecodewithexplanationincludedinwhichwesetthegreencolorfordisplayedhintofaedittext. SettingtextColorHintinEditTextInJavaclass: Belowistheexamplecodeinwhichwesetthehintcolorofaedittextprogrammaticallymeansinjavaclass. EditTextsimpleEditText=(EditText)findViewById(R.id.simpleEditText); simpleEditText.setHintTextColor(Color.green(0));//setthegreenhintcolor 7.textSize:textSizeattributeisusedtosetthesizeoftextofaedittext.Wecansetthetextsizeinsp(scaleindependentpixel)ordp(densitypixel). Belowistheexamplecodeinwhichwesetthe25spsizeforthetextofaedittext. SettingtextSizeinEditTextinJavaclass: Belowistheexamplecodeinwhichwesetthetextsizeofaedittextprogrammaticallymeansinjavaclass. EditTextsimpleEditText=(EditText)findViewById(R.id.simpleEditText); simpleEditText.setTextSize(25);//setsizeoftext 8.textStyle:textStyleattributeisusedtosetthetextstyleofaedittext.Thepossibletextstylesarebold,italicandnormal.Ifweneedtousetwoormorestylesforaedittextthen“|”operatorisusedforthat. Belowistheexamplecodewithexplanationincluded,inwhichwesettheboldanditalictextstylesfortext. 9.background:backgroundattributeisusedtosetthebackgroundofaedittext.Wecansetacolororadrawableinthebackgroundofaedittext. Belowistheexamplecodewithexplanationincludedinwhichwesettheblackcolorforthebackground,whitecolorforthedisplayedhintandset10dppaddingfromalltheside’sforedittext. SettingBackgroundinEditTextInJavaclass: Belowistheexamplecodeinwhichwesetthebackgroundcolorofaedittextprogrammaticallymeansinjavaclass. EditTextsimpleEditText=(EditText)findViewById(R.id.simpleEditText); simpleEditText.setBackgroundColor(Color.BLACK);//setblackbackgroundcolor 10.padding:paddingattributeisusedtosetthepaddingfromleft,right,toporbottom.Inaboveexamplecodeofbackgroundwealsosetthe10dppaddingfromalltheside’sofedittext. ExampleI–EditTextinAndroidStudio BelowistheexampleofedittextinwhichwegetthevaluefrommultipleedittextsandonbuttonclickeventtheToastwillshowthedatadefinedinEdittext. DownloadCode? Step1:CreateanewprojectinAndroidStudioandnameitEditTextExample. Step2:NowOpenres->layout-> xml(or)activity_main.xml andaddfollowingcode.Inthiscodewehaveaddedmultipleedittextandabuttonwithonclickfunctionality. Step3:Nowopenapp->java->package->MainActivity.javaandaddthebelowcode. Inthiswejustfetchthetextfromtheedittext,furtherwiththebuttonclickeventatoastwillshowthetextfetchedbefore. packagecom.example.edittextexample; importandroid.support.v7.app.AppCompatActivity; importandroid.os.Bundle; importandroid.view.View; importandroid.widget.Button; importandroid.widget.EditText; importandroid.widget.Toast; publicclassMainActivityextendsAppCompatActivity{ Buttonsubmit; EditTextname,password,email,contact,date; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name=(EditText)findViewById(R.id.editText1); password=(EditText)findViewById(R.id.editText2); email=(EditText)findViewById(R.id.editText3); date=(EditText)findViewById(R.id.editText4); contact=(EditText)findViewById(R.id.editText5); submit=(Button)findViewById(R.id.button); submit.setOnClickListener(newView.OnClickListener(){ @Override publicvoidonClick(Viewv){ if(name.getText().toString().isEmpty()||password.getText().toString().isEmpty()||email.getText().toString().isEmpty()||date.getText().toString().isEmpty() ||contact.getText().toString().isEmpty()){ Toast.makeText(getApplicationContext(),"EntertheData",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(),"Name-"+name.getText().toString()+"\n"+"Password-"+password.getText().toString() +"\n"+"E-Mail-"+email.getText().toString()+"\n"+"Date-"+date.getText().toString() +"\n"+"Contact-"+contact.getText().toString(),Toast.LENGTH_SHORT).show(); } } }); } } Output: NowstarttheAVDinEmulatorandruntheApp.Youwillseescreenaskingyoutofillthedatainrequiredfieldslikename,password(numeric),email,date,contactnumber.Enterdataandclickonbutton.YouwillseethedataenteredwillbedisplayedasToastonscreen. ExampleII–EditTextinAndroidStudio BelowistheexampleofedittextinwhichwegetthevaluefromaedittextonbuttonclickeventandthendisplayitinaToast.Belowisthefinaloutputandcode. DownloadCode? Step1:CreateanewprojectinAndroidStudioandnameitEditTextExample. SelectFile->New->NewProjectandFilltheformsandclick"Finish"button. Step2:NowOpenres->layout-> xml(or)activity_main.xml andaddfollowingcode.HerewewilldesignoneEditTextforfillingnameandoneButtonwhichwillbeusedtodisplaythenameenteredbytheuser. Step3:Nowopenapp->java->package-> MainActivity.javaandaddthebelowcode.Theexplanationisincludedinthecodeitselfascomment. packageexample.abhiandriod.edittextexample; importandroid.graphics.Color; importandroid.support.v7.app.AppCompatActivity; importandroid.os.Bundle; importandroid.view.Menu; importandroid.view.MenuItem; importandroid.view.View; importandroid.widget.Button; importandroid.widget.EditText; importandroid.widget.Toast; publicclassMainActivityextendsAppCompatActivity{ @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); finalEditTextsimpleEditText=(EditText)findViewById(R.id.simpleEditText);//gettheidforedittext ButtondisplayText=(Button)findViewById(R.id.displayText);//gettheidforbutton displayText.setOnClickListener(newView.OnClickListener(){ @Override publicvoidonClick(Viewview){ if(simpleEditText.getText().toString()!=null)//checkwhethertheenteredtextisnotnull { Toast.makeText(getApplicationContext(),simpleEditText.getText().toString(),Toast.LENGTH_LONG).show();//displaythetextthatyouenteredinedittext } } }); } } Output: NowstarttheAVDinEmulatorandruntheApp.Youwillseescreenaskingyoutofillyourname.Enteryournameandclickonbutton.YouwillseethenameenteredwillbedisplayedasToastonscreen. TextInputLayout/FloatingLabelsInEditText: TextInputLayoutisanewelementintroducedinMaterialDesignSupportlibrarytodisplaythefloatinglabelin EditText.Readouradvance FloatingLabelstutorialtolearnhowtouseitinyourApp. DOWNLOADTHISFREEeBook! ThisfreeeBookwillhelpyoumasterthelearningofAndroidAppDevelopmentinAndroidStudio! Name Email Subscribe&DownloadeBookNow>> 5thoughtson“EditTextTutorialWithExampleInAndroidStudio:InputField” nice…..veryuseful Reply HowcanIremovetheautotabsetting/functionoftheEditTextatenter? Reply Hello Howdoyoufind“EditText”afterdecompilewithapktool? Reply cumi6x Reply Awesome!!! Reply LeaveaReplyCancelreplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*CommentName* Email* Website Savemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment. ContinueReading: CustomSpinnerEditTextTutorialWithExampleinAndroidStudio TextViewTutorialWithExampleinAndroidStudio ButtonTutorialWithExampleinAndroidStudio ImageViewTutorialWithExampleinAndroidStudio AllscaleTypeInImageViewWithExampleTutorialWithExampleinAndroidStudio DOWNLOADTHISFREEeBook! ThisfreeeBookwillhelpyoumasterthelearningofAndroidAppDevelopmentinAndroidStudio! Name Email Subscribe&DownloadeBookNow>> PremiumProjectSourceCode: FoodOrderingAndroidAppProjectSourceCode EcommerceStoreAndroidAppProjectSourceCode ConvertWebsiteIntoAndroidAppProjectSourceCode QuizGameAndroidAppProjectSourceCode RadioStreamingAndroidAppSourceCode CityGuideAndroidAppProjectSourceCode QRBarcodeAndroidAppProjectSourceCode DOWNLOADTHISFREEeBook! ThisfreeeBookwillhelpyoumasterthelearningofAndroidAppDevelopmentinAndroidStudio! Name Email Subscribe&DownloadeBookNow>> SeeHowAbhiAndroid StepByStep VideoTrainingHelpsYouMasterAndroidAppDevelopment VideoTraining- Unlockstepbystepvideotrainingwithnewcontentaddedregularly.DevelopAndroidApps. AndroidAppSourceCode- GetamazingEcommerce,FoodOrderingandUltimateWebViewsourcecodewithdocumentation. GETACCESSNOW



請為這篇文章評分?