Sie sind auf Seite 1von 9

3/28/2016 Layouts | Android Developers

Layouts
Alayoutdefinesthevisualstructureforauserinterface,such
astheUIforanactivityorappwidget.Youcandeclarealayout Inthisdocument
intwoways:
WritetheXML
DeclareUIelementsinXML.Androidprovidesa LoadtheXMLResource
straightforwardXMLvocabularythatcorrespondstothe
Viewclassesandsubclasses,suchasthoseforwidgetsand Attributes
layouts. ID
Instantiatelayoutelementsatruntime.Yourapplication LayoutParameters
cancreateViewandViewGroupobjects(andmanipulate LayoutPosition
theirproperties)programmatically. Size,PaddingandMargins
TheAndroidframeworkgivesyoutheflexibilitytouseeither CommonLayouts
orbothofthesemethodsfordeclaringandmanagingyour BuildingLayoutswithan
application'sUI.Forexample,youcoulddeclareyour Adapter
application'sdefaultlayoutsinXML,includingthescreen
Fillinganadapterview
elementsthatwillappearinthemandtheirproperties.You withdata
couldthenaddcodeinyourapplicationthatwouldmodifythe
stateofthescreenobjects,includingthosedeclaredinXML,at Handlingclickevents
runtime.
Keyclasses
TheadvantagetodeclaringyourUIinXMListhatitenables
youtobetterseparatethepresentationofyourapplicationfrom View
thecodethatcontrolsitsbehavior.YourUIdescriptionsare
ViewGroup
externaltoyourapplicationcode,whichmeansthatyoucan
modifyoradaptitwithouthavingtomodifyyoursourcecode ViewGroup.LayoutParams
andrecompile.Forexample,youcancreateXMLlayoutsfor
differentscreenorientations,differentdevicescreensizes,and
differentlanguages.Additionally,declaringthelayoutinXML Seealso
makesiteasiertovisualizethestructureofyourUI,soit's BuildingaSimpleUser
easiertodebugproblems.Assuch,thisdocumentfocuseson Interface
teachingyouhowtodeclareyourlayoutinXML.Ifyou're
interestedininstantiatingViewobjectsatruntime,referto
the ViewGroupand Viewclassreferences.
YoushouldalsotrytheHierarchy
Ingeneral,theXMLvocabularyfordeclaringUIelements Viewertool,fordebugginglayouts
closelyfollowsthestructureandnamingoftheclassesand itrevealslayoutpropertyvalues,draws
methods,whereelementnamescorrespondtoclassnames wireframeswithpadding/margin
andattributenamescorrespondtomethods.Infact,the indicators,andfullrenderedviews
correspondenceisoftensodirectthatyoucanguesswhat whileyoudebugontheemulatoror
XMLattributecorrespondstoaclassmethod,orguesswhat device.
classcorrespondstoagivenXMLelement.However,note
thatnotallvocabularyisidentical.Insomecases,thereare Thelayoutopttoolletsyouquickly
slightnamingdifferences.Forexample,theEditText analyzeyourlayoutsandhierarchies
elementhasa textattributethatcorresponds forinefficienciesorotherproblems.

http://developer.android.com/guide/topics/ui/declaring-layout.html 1/9
3/28/2016 Layouts | Android Developers

to EditText.setText().

Tip:LearnmoreaboutdifferentlayouttypesinCommonLayoutObjects.

WritetheXML
UsingAndroid'sXMLvocabulary,youcanquicklydesignUIlayoutsandthescreenelementsthey
contain,inthesamewayyoucreatewebpagesinHTMLwithaseriesofnestedelements.
Eachlayoutfilemustcontainexactlyonerootelement,whichmustbeaVieworViewGroupobject.
Onceyou'vedefinedtherootelement,youcanaddadditionallayoutobjectsorwidgetsaschildelements
tograduallybuildaViewhierarchythatdefinesyourlayout.Forexample,here'sanXMLlayoutthatuses
avertical LinearLayouttoholda TextViewanda Button:

<?xmlversion="1.0"encoding="utf8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextViewandroid:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello,IamaTextView"/>
<Buttonandroid:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello,IamaButton"/>
</LinearLayout>

Afteryou'vedeclaredyourlayoutinXML,savethefilewiththe .xmlextension,inyourAndroid
project's res/layout/directory,soitwillproperlycompile.

MoreinformationaboutthesyntaxforalayoutXMLfileisavailableintheLayoutResourcesdocument.

LoadtheXMLResource
Whenyoucompileyourapplication,eachXMLlayoutfileiscompiledintoa Viewresource.You
shouldloadthelayoutresourcefromyourapplicationcode,inyour Activity.onCreate()callback
implementation.Dosobycalling setContentView() ,passingitthereferencetoyourlayoutresource
intheformof: R.layout.layout_file_name.Forexample,ifyourXMLlayoutissaved
as main_layout.xml,youwouldloaditforyourActivitylikeso:

publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState)
setContentView(R.layout.main_layout)
}

http://developer.android.com/guide/topics/ui/declaring-layout.html 2/9
3/28/2016 Layouts | Android Developers

The onCreate()callbackmethodinyourActivityiscalledbytheAndroidframeworkwhenyour
Activityislaunched(seethediscussionaboutlifecycles,intheActivitiesdocument).

Attributes
EveryViewandViewGroupobjectsupportstheirownvarietyofXMLattributes.Someattributesare
specifictoaViewobject(forexample,TextViewsupportsthe textSizeattribute),buttheseattributes
arealsoinheritedbyanyViewobjectsthatmayextendthisclass.SomearecommontoallViewobjects,
becausetheyareinheritedfromtherootViewclass(likethe idattribute).And,otherattributesare
considered"layoutparameters,"whichareattributesthatdescribecertainlayoutorientationsoftheView
object,asdefinedbythatobject'sparentViewGroupobject.

ID
AnyViewobjectmayhaveanintegerIDassociatedwithit,touniquelyidentifytheViewwithinthetree.
Whentheapplicationiscompiled,thisIDisreferencedasaninteger,buttheIDistypicallyassignedin
thelayoutXMLfileasastring,inthe idattribute.ThisisanXMLattributecommontoallView
objects(definedbythe Viewclass)andyouwilluseitveryoften.ThesyntaxforanID,insideanXML
tagis:

android:id="@+id/my_button"

Theatsymbol(@)atthebeginningofthestringindicatesthattheXMLparsershouldparseandexpand
therestoftheIDstringandidentifyitasanIDresource.Theplussymbol(+)meansthatthisisanew
resourcenamethatmustbecreatedandaddedtoourresources(inthe R.javafile).Thereareanumber
ofotherIDresourcesthatareofferedbytheAndroidframework.WhenreferencinganAndroidresource
ID,youdonotneedtheplussymbol,butmustaddthe androidpackagenamespace,likeso:

android:id="@android:id/empty"

Withthe androidpackagenamespaceinplace,we'renowreferencinganIDfrom
the android.Rresourcesclass,ratherthanthelocalresourcesclass.

Inordertocreateviewsandreferencethemfromtheapplication,acommonpatternisto:
1.Defineaview/widgetinthelayoutfileandassignitauniqueID:

<Buttonandroid:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/my_button_text"/>

2.Thencreateaninstanceoftheviewobjectandcaptureitfromthelayout(typicallyin
the onCreate() method):

ButtonmyButton=(Button)findViewById(R.id.my_button)

http://developer.android.com/guide/topics/ui/declaring-layout.html 3/9
3/28/2016 Layouts | Android Developers

DefiningIDsforviewobjectsisimportantwhencreatinga RelativeLayout.Inarelativelayout,
siblingviewscandefinetheirlayoutrelativetoanothersiblingview,whichisreferencedbytheunique
ID.
AnIDneednotbeuniquethroughouttheentiretree,butitshouldbeuniquewithinthepartofthetree
youaresearching(whichmayoftenbetheentiretree,soit'sbesttobecompletelyuniquewhenpossible).

LayoutParameters
XMLlayoutattributesnamed layout_somethingdefinelayoutparametersfortheViewthatare
appropriatefortheViewGroupinwhichitresides.
EveryViewGroupclassimplementsanestedclassthatextends ViewGroup.LayoutParams.Thissubclass
containspropertytypesthatdefinethesizeandpositionforeachchildview,asappropriatefortheview
group.Asyoucanseeinfigure1,theparentviewgroupdefineslayoutparametersforeachchildview
(includingthechildviewgroup).

Figure1.Visualizationofaviewhierarchywithlayoutparametersassociatedwitheachview.

NotethateveryLayoutParamssubclasshasitsownsyntaxforsettingvalues.Eachchildelementmust
defineLayoutParamsthatareappropriateforitsparent,thoughitmayalsodefinedifferentLayoutParams
foritsownchildren.
Allviewgroupsincludeawidthandheight( layout_widthand layout_height),andeachviewis
requiredtodefinethem.ManyLayoutParamsalsoincludeoptionalmarginsandborders.
Youcanspecifywidthandheightwithexactmeasurements,thoughyouprobablywon'twanttodothis
often.Moreoften,youwilluseoneoftheseconstantstosetthewidthorheight:
wrap_contenttellsyourviewtosizeitselftothedimensionsrequiredbyitscontent.
match_parent(namedfill_parentbeforeAPILevel8)tellsyourviewtobecomeasbigasitsparent
http://developer.android.com/guide/topics/ui/declaring-layout.html 4/9
3/28/2016 Layouts | Android Developers

viewgroupwillallow.

Ingeneral,specifyingalayoutwidthandheightusingabsoluteunitssuchaspixelsisnotrecommended.
Instead,usingrelativemeasurementssuchasdensityindependentpixelunits(dp),wrap_content,
ormatch_parent,isabetterapproach,becauseithelpsensurethatyourapplicationwilldisplayproperly
acrossavarietyofdevicescreensizes.TheacceptedmeasurementtypesaredefinedintheAvailable
Resourcesdocument.

LayoutPosition
Thegeometryofaviewisthatofarectangle.Aviewhasalocation,expressedasapair
ofleftandtopcoordinates,andtwodimensions,expressedasawidthandaheight.Theunitforlocation
anddimensionsisthepixel.
Itispossibletoretrievethelocationofaviewbyinvokingthemethods getLeft()and getTop().The
formerreturnstheleft,orX,coordinateoftherectanglerepresentingtheview.Thelatterreturnsthetop,
orY,coordinateoftherectanglerepresentingtheview.Thesemethodsbothreturnthelocationofthe
viewrelativetoitsparent.Forinstance,when getLeft()returns20,thatmeanstheviewislocated20
pixelstotherightoftheleftedgeofitsdirectparent.
Inaddition,severalconveniencemethodsareofferedtoavoidunnecessarycomputations,
namely getRight()and getBottom().Thesemethodsreturnthecoordinatesoftherightandbottom
edgesoftherectanglerepresentingtheview.Forinstance,calling getRight()issimilartothefollowing
computation: getLeft()+getWidth().

Size,PaddingandMargins
Thesizeofaviewisexpressedwithawidthandaheight.Aviewactuallypossesstwopairsofwidthand
heightvalues.
Thefirstpairisknownasmeasuredwidthandmeasuredheight.Thesedimensionsdefinehowbigaview
wantstobewithinitsparent.Themeasureddimensionscanbeobtainedby
calling getMeasuredWidth()and getMeasuredHeight().

Thesecondpairissimplyknownaswidthandheight,orsometimesdrawingwidthanddrawingheight.
Thesedimensionsdefinetheactualsizeoftheviewonscreen,atdrawingtimeandafterlayout.These
valuesmay,butdonothaveto,bedifferentfromthemeasuredwidthandheight.Thewidthandheight
canbeobtainedbycalling getWidth()and getHeight().

Tomeasureitsdimensions,aviewtakesintoaccountitspadding.Thepaddingisexpressedinpixelsfor
theleft,top,rightandbottompartsoftheview.Paddingcanbeusedtooffsetthecontentoftheviewbya
specificnumberofpixels.Forinstance,aleftpaddingof2willpushtheview'scontentby2pixelstothe
rightoftheleftedge.Paddingcanbesetusingthe setPadding(int,int,int,int)methodand
queriedby
calling getPaddingLeft(), getPaddingTop(), getPaddingRight()and getPaddingBottom().
Eventhoughaviewcandefineapadding,itdoesnotprovideanysupportformargins.However,view
groupsprovidesuchasupport.Referto ViewGroupand ViewGroup.MarginLayoutParamsforfurther
information.
http://developer.android.com/guide/topics/ui/declaring-layout.html 5/9
3/28/2016 Layouts | Android Developers

Formoreinformationaboutdimensions,seeDimensionValues.

CommonLayouts
Eachsubclassofthe ViewGroupclassprovidesauniquewaytodisplaytheviewsyounestwithinit.
BelowaresomeofthemorecommonlayouttypesthatarebuiltintotheAndroidplatform.

Note:AlthoughyoucannestoneormorelayoutswithinanotherlayouttoacheiveyourUIdesign,
youshouldstrivetokeepyourlayouthierarchyasshallowaspossible.Yourlayoutdrawsfasterifit
hasfewernestedlayouts(awideviewhierarchyisbetterthanadeepviewhierarchy).

LinearLayout RelativeLayout WebView

Alayoutthatorganizesits Enablesyoutospecifythe Displayswebpages.


childrenintoasingle locationofchildobjects
horizontalorverticalrow.It relativetoeachother(childA
createsascrollbarifthelength totheleftofchildB)ortothe
ofthewindowexceedsthe parent(alignedtothetopof
lengthofthescreen. theparent).

BuildingLayoutswithanAdapter
Whenthecontentforyourlayoutisdynamicornotpredetermined,youcanusealayoutthat
subclasses AdapterViewtopopulatethelayoutwithviewsatruntime.Asubclassof
the AdapterViewclassusesan Adaptertobinddatatoitslayout.The Adapterbehavesasa
middlemanbetweenthedatasourceandthe AdapterViewlayoutthe Adapterretrievesthedata(from
asourcesuchasanarrayoradatabasequery)andconvertseachentryintoaviewthatcanbeaddedinto
the AdapterViewlayout.
Commonlayoutsbackedbyanadapterinclude:

ListView GridView

http://developer.android.com/guide/topics/ui/declaring-layout.html 6/9
3/28/2016 Layouts | Android Developers

Displaysascrollingsingle Displaysascrollinggridof
columnlist. columnsandrows.

Fillinganadapterviewwithdata
Youcanpopulatean AdapterViewsuchas ListViewor GridViewbybinding
the AdapterViewinstancetoan Adapter,whichretrievesdatafromanexternalsourceandcreates
a Viewthatrepresentseachdataentry.
Androidprovidesseveralsubclassesof Adapterthatareusefulforretrievingdifferentkindsofdataand
buildingviewsforan AdapterView.Thetwomostcommonadaptersare:

ArrayAdapter

Usethisadapterwhenyourdatasourceisanarray.Bydefault, ArrayAdaptercreatesaviewfor
eacharrayitembycalling toString()oneachitemandplacingthecontentsina TextView.
Forexample,ifyouhaveanarrayofstringsyouwanttodisplayina ListView,initializea
new ArrayAdapterusingaconstructortospecifythelayoutforeachstringandthestringarray:

ArrayAdapter<String>adapter=newArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,myStringArray)

Theargumentsforthisconstructorare:
Yourapp Context
Thelayoutthatcontainsa TextViewforeachstringinthearray
Thestringarray

Thensimplycall setAdapter()onyour ListView:

ListViewlistView=(ListView)findViewById(R.id.listview)
listView.setAdapter(adapter)

Tocustomizetheappearanceofeachitemyoucanoverridethe toString()methodforthe
objectsinyourarray.Or,tocreateaviewforeachitemthat'ssomethingotherthan
a TextView(forexample,ifyouwantan ImageViewforeacharrayitem),extend
http://developer.android.com/guide/topics/ui/declaring-layout.html 7/9
3/28/2016 Layouts | Android Developers

the ArrayAdapterclassandoverride getView()toreturnthetypeofviewyouwantforeach


item.

SimpleCursorAdapter

Usethisadapterwhenyourdatacomesfroma Cursor.Whenusing SimpleCursorAdapter,you


mustspecifyalayouttouseforeachrowinthe Cursorandwhichcolumnsinthe Cursorshould
beinsertedintowhichviewsofthelayout.Forexample,ifyouwanttocreatealistofpeople's
namesandphonenumbers,youcanperformaquerythatreturnsa Cursorcontainingarowfor
eachpersonandcolumnsforthenamesandnumbers.Youthencreateastringarrayspecifying
whichcolumnsfromthe Cursoryouwantinthelayoutforeachresultandanintegerarray
specifyingthecorrespondingviewsthateachcolumnshouldbeplaced:

String[]fromColumns={ContactsContract.Data.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER}
int[]toViews={R.id.display_name,R.id.phone_number}

Whenyouinstantiatethe SimpleCursorAdapter,passthelayouttouseforeachresult,
the Cursorcontainingtheresults,andthesetwoarrays:

SimpleCursorAdapteradapter=newSimpleCursorAdapter(this,
R.layout.person_name_and_number,cursor,fromColumns,toViews,0)
ListViewlistView=getListView()
listView.setAdapter(adapter)

The SimpleCursorAdapterthencreatesaviewforeachrowinthe Cursorusingtheprovided


layoutbyinsertingeach fromColumnsitemintothecorresponding toViewsview.

If,duringthecourseofyourapplication'slife,youchangetheunderlyingdatathatisreadbyyour
adapter,youshouldcall notifyDataSetChanged().Thiswillnotifytheattachedviewthatthedatahas
beenchangedanditshouldrefreshitself.

Handlingclickevents
Youcanrespondtoclickeventsoneachiteminan AdapterViewbyimplementing
the AdapterView.OnItemClickListenerinterface.Forexample:

//Createamessagehandlingobjectasananonymousclass.
privateOnItemClickListenermMessageClickedHandler=newOnItemClickListener(){
publicvoidonItemClick(AdapterViewparent,Viewv,intposition,longid){
//Dosomethinginresponsetotheclick
}
}

listView.setOnItemClickListener(mMessageClickedHandler)
http://developer.android.com/guide/topics/ui/declaring-layout.html 8/9
3/28/2016 Layouts | Android Developers


Getnews&tips

http://developer.android.com/guide/topics/ui/declaring-layout.html 9/9

Das könnte Ihnen auch gefallen