Você está na página 1de 11

CreatingaUserInterfaceusingXML

Prerequisites
BeforestartingwiththistutorialyoushouldhavereadAndroidSDKandEclipseIDE,orsomeother HelloWorldliketutorialonAndroid.IfyouuseacomputeratCampusHaninge,readappendixAin thetutorialmentionedabove. AlthoughyoucanfindaprojectwiththesolutiontothisexerciseatBilda,thebestwaytolearnthe basicsoncreatinguserinterfacesinAndroidistodoityourself,usingthetoolsinEclipseasdescribed inthetext.

Introduction
WhendevelopinganAndroidapplicationyoushoulddefinethecomponentsandtheirpropertiesin youruserinterfaceusingXML.Althoughyoucandefinethecomponentsinthesourcecode,itsgood practicetoseparatethisfromtherestofthecode(thecodedealingwiththeapplicationsevent handlingandlogic). InthisexerciseyouwilldefineasimpleuserinterfaceinXML,usingthelayouteditorinEclipse.The goalisauserinterface,UI,liketheonebelow.

Createaproject
CreateanewAndroidprojectwiththefollowingproperties: Projectname,TemperatureConverter Buildtarget,Android2.1 ApplicationName,TemperatureConverter

PackageName,se.kth.temperature CreateActivity,TemperatureActivity MinSDKversion,7

BuildingtheUIusingtheXMLeditorinEclipse
Openthefileres/layout/main.xml.Thisiswherethelayoutofyour(main)UIisdefined.Usethetabs atthebottomtoswitchbetweentheGraphicallayoutandtheXMLcodedefiningthelayout.

TheUIcontainsaLinearLayoutwithaTextViewpresentingatext(@string/helloisdefinedin res/values/string.xml). SwitchtoXML(thetabmain.xmlatthebottomofthepanel).Itshouldlooklikethis:


<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"

android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>

SwitchbacktographicallayoutandremovetheTextView;rightclickitandselectdelete.Switchto XMLviewagainandcheckthattheTextViewisremoved.

AddingViews
Remember,inanAndroid,aViewcanbeanatomicUIcomponent,aButton,TextVieworsuch,orit canbeacontainer,ViewGroup,forexamplealayoutcomponent. LetsaddsomeviewcomponentsinourLinerLayout.Switchtographicallayout. FirstaddaTextViewfortextinput;clickonEditTextintherightpanel,thendraganddropthe componentontothelayout.

ManagingViewproperties
TomanagethepropertiesforthisEditText,rightclickthecomponentandselect ShowIn/Properties.Anewtab,Properties,isopenedbelowthegraphicallayout.Here,youcanset propertiesfortheEditText. Forexample,tochangethetextsize,browsetothecorrespondinglineandsetthevalue16sp (scaledpixels).

Alsoset/changethesepropertiesfortheEditTextcomponent: Hint Id Inputatemperature @+id/TextInput Textdisplayedwheninputisempty Thisistheidusedwhenreferencingthisviewfrom yoursourcecode.Mustbeginwith@+id/ Thisallowsonlydecimalnumberinput Singleline Thedisplayedtexts,inthiscasenone. Musthaveaunit,sp=scale-independent pixels. Usethedropdownmenutobrowsethealternatives

Inputtype numberDecimal Lines 1 Text Textsize 16sp Layoutwidth fill_parent YourXMLfileshouldcontainthisinformation(thoughthelinebreaksandtheindentationmightbe differentinyourversion):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"

android:layout_width="fill_parent" android:layout_height="fill_parent" > <EditText android:layout_height="wrap_content" android:textSize="16sp" android:lines="1" android:id="@+id/TextInput" android:layout_width="fill_parent" android:hint="Input a temperature" android:inputType="numberDecimal" > </EditText> </LinearLayout>

Addingmoreviews
Inthesamewayasdescribedabove,addthefollowingusingdraganddrop. ARadioGroup(alayout) IntheRadioGroup,twoRadioButtons.MakesureyoudroptheminsidetheRadioGroup (checkthexmlcode) Abutton ATextView(fortheoutput)

FortheRadioButtons,settheId,TextandTextsizepropertiesto @+id/CelciusButton,ToFahrenheit,16spand@+id/FahrenheitButton,ToCelcius,16sp respectively. SetthesamepropertiesfortheButtonto@+id/CalculateButton,Calculateand16sp respectively. FortheTextView,set@+id/TextOutput,and16sp. TheXMLcodeshould,moreorless,looklikebelow.MakesuretheRadioButtonsaredefinedinside theRadioGroup.

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <EditText android:layout_height="wrap_content" android:textSize="16sp" android:lines="1" android:id="@+id/TextInput" android:layout_width="fill_parent" android:hint="Input a temperature" android:inputType="numberDecimal" > </EditText> <RadioGroup android:id="@+id/RadioGroup01" android:layout_width="wrap_content" android:layout_height="wrap_content" > <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" android:text="To Celcius" android:id="@+id/CelciusButton" > </RadioButton> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/FahrenheitButton" android:text="To Fahrenheit" android:textSize="16sp" > </RadioButton> </RadioGroup> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" android:text="Calculate" android:id="@+id/CalculateButton" > </Button> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextOutput" android:textSize="16sp" > </TextView> </LinearLayout>

Runtheapplication
TocheckoutwhatyourUIlookslike,runtheapplication;rightclicktheprojectheaderandselect RunAs/AndroidApplication.TheUIshouldlooklikebelow.

Atruntime,theuserinterfacecomponentsarecreatedfromtheinformationintheXMLfile. Theline setContentView(R.layout.main); intheTemperatureActivity.javatellstheapplicationwhichlayoutfiletouse(thenameofourlayout fileismain.xml). Youcanhavemultiplelayoutfilesinourapplicationandthusdefinemultiplelayouts.

AccessingUIcomponentsinthesourcecode
YoucanaccesstheUIcomponents,definedintheXMLfile,fromyourapplicationcodethroughtheir ids(e.g.@+id/TextInputfortheEditTextcomponent)andthefindViewByIdmethod. OpenTemperatureActivity.javaandaddamemberrepresentingtheExitTextandthencall findViewByIdtogetareferencetothecomponent.
public class TemperatureActivity extends Activity { private EditText textInput; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textInput = (EditText) findViewById(R.id.TextInput); }

Addcodetoreferencethebuttonsaswell. Wethenhavetodefinewhatshouldhappenwhenthecalculatebuttonispressed(gettheinput fromtheEditTextandconvertthevaluetodegreesCelsiusorFahrenheit).Thisisdoneinaclass implementingthecallbackinterfaceView.OnClickListener.Belowyoufindthecompletecode.


public class TemperatureActivity extends Activity { private private private private private EditText textInput ; RadioButton celciusButton; RadioButton fahrenheitButton; Button calculateButton; TextView textOutput;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textInput = (EditText) findViewById(R.id.TextInput); celciusButton = (RadioButton) findViewById(R.id.CelciusButton); fahrenheitButton = (RadioButton) findViewById(R.id.FahrenheitButton); calculateButton = (Button) findViewById(R.id.CalculateButton); textOutput = (TextView) findViewById(R.id.TextOutput); // Create a listener instance and associate it with the button OnClickListener listener = new ButtonListener(); calculateButton.setOnClickListener(listener); } /** * This class defines the action to take when the calculate button * is clicked, in this case by calling buttonClickHandler(). */ private class ButtonListener implements OnClickListener { @Override public void onClick(View v) { buttonClickHandler(); } } private void buttonClickHandler() { String text = textInput.getText().toString(); if(text.length() == 0) { showToast("Please enter a a valid number"); return; } float value = Float.parseFloat(text); String result = ""; if(celciusButton.isChecked()) { float c = convertFahrenheitToCelsius(value); result = "" + c + " Celsius"; } else if(fahrenheitButton.isChecked()) { float f = convertCelsiusToFahrenheit(value); result = "" + f + " Fahrenheit"; } else { showToast("Please select a radio button");

return; } textOutput.setText(result); } private float convertFahrenheitToCelsius(float fahrenheit) { return ((fahrenheit - 32) * 5 / 9); } private float convertCelsiusToFahrenheit(float celsius) { return ((celsius * 9) / 5) + 32; } private void showToast(String msg) { Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT); toast.show(); } }

Wheretogofromhere
Irecommendyoutocontinuewithamoreelaboratetutorial,theNotePadTutorial(13)at http://developer.android.com/resources/tutorials/notepad/index.html. Therearealotofgoodtutorialsonuserinterfaces,andothertopics,at http://developer.android.com/resources/tutorials/.

DeclaringthecallbackmethodintheXMLfile
InsteadofdefininganOnClickListenerinyourcode,youmayreferencethemethodtocallbysetting theonClickpropertyforthebutton. Inthiscase,wewanttoreferencethebuttonClickHandlermethodfromtheXMLfile.Inthelayout manager,selectthebuttonandsetthepropertyonClicktobuttonClickHandler. Inthiscase,themethodmusthavepublicvisibility,andanargumentoftypeview,i.e.
public void buttonClickHandler(View view) {

TheresnoneedforanexplicitOnClickListnerinthiscase;removethelinesdefiningtheclass implementingtheOnClickListenerinterface.
public class TemperatureActivity2 extends Activity { private private private private private EditText textInput ; RadioButton celciusButton; RadioButton fahrenheitButton; Button calculateButton; TextView textOutput;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textInput = (EditText) findViewById(R.id.TextInput); celciusButton = (RadioButton) findViewById(R.id.CelciusButton); fahrenheitButton = (RadioButton) findViewById(R.id.FahrenheitButton); calculateButton = (Button) findViewById(R.id.CalculateButton); textOutput = (TextView) findViewById(R.id.TextOutput); } /** * Because we set the property onClick for the Button to reference this * method we don't have to implement the OnClickListener explicitly. * NB: The method to handle the event must not be private and * must have an argument of type View. */ public void buttonClickHandler(View view) { String text = textInput.getText().toString(); if(text.length() == 0) { showToast("Please enter a a valid number"); return; } (continues as in previous example)

TheprojectTemperatureConverter2containsthecompleteimplementationofthisversionofthe application.

Multiplelayoutsorotherresources
ToaddadditionalXMLfilesdefininglayouts,orotherresources,rightclickontheprojectheaderand selectAndroidTools/NewResourceFile.

Você também pode gostar