Sei sulla pagina 1di 9

12/30/2014

Home

AndroidHeaderandFooterlayoutexample|JavaCodeGeeks
Tutorials

Java

Android

JoinUs

About

Resources

JVMLanguages

JobBoard

Examples

SoftwareDevelopment

Agile

Whitepapers

DevOps

Academy

Communications

Career

Misc

Searchthissite...

MetaJCG

Youarehere:Home AndroidCore AndroidHeaderandFooterlayoutexample

December30,20145:51pm

AboutNikosMaravitsas
NikoshasgraduatedfromtheDepartmentofInformaticsandTelecommunicationsofTheNationalandKapodistrianUniversity
ofAthens.Currently,hismaininterestsaresystemssecurity,parallelsystems,artificialintelligence,operatingsystems,system
programming,telecommunications,webapplications,humanmachineinteractionandmobiledevelopment.

Newsletter

66258insidersarealreadyenjoyingweekly

AndroidHeaderandFooterlayoutexample

updatesandcomplimentarywhitepapers!

Jointhemnowtogainexclusiveaccess

byNikosMaravitsasonOctober1st,2013 | Filedin:AndroidCore

tothelatestnewsintheJavaworld,aswellas

InthisarticlewearegoingtoseehowyoucancreateasimpleAndroidLayoutthatincludesaheaderpart,afooterpartandthecontent

insightsaboutAndroid,Scala,Groovyandother

area.ItisrelativelyeasytodothatintheAndroidplatform.Theimportantbitistotrytomakeyourlayoutsreusableandindependent

relatedtechnologies.

fromoneanother,soyoucanuseitanywhereinyourapplication,notjustinoneActivity.Sothatswhatarewegoingtodointhis
example.
Forthistutorial,wewillusethefollowingtoolsinaWindows64bitplatform:
1. JDK1.7

Emailaddress:
Youremailaddress
Signup

2. Eclipse4.3Kepler
3. AndroidSKD4.3

JoinUs

JoinUs

1.CreateanewAndroidProject

With 819,138 monthly


uniquevisitorsandover 500
authorsweareplacedamong

OpenEclipseIDEandgotoFile>New>Project>Android>AndroidApplicationProject.

thetopJavarelatedsites
around.Constantlybeingon
thelookoutforpartnerswe
encourageyoutojoinus.So
Ifyouhaveablogwithuniqueandinteresting
contentthenyoushouldcheckoutourJCG
partnersprogram.Youcanalsobeaguestwriter
forJavaCodeGeeksandhoneyourwritingskills!
RecentJobs

SoftwareTester
Springfield,VA

EntryLevelSoftwareDeveloper:Atlana,GAJob
Atlanta,GA

TechnicalBusinessAnalyst/ApplicationSupport
NewYork,NY

JavaWebApplicationDeveloperSr.
ThousandOaks,CA

LeadApplicationsDeveloper
NewBritain,CT

ViewAll

YouhavetospecifytheApplicationName,theProjectNameandthePackagenameintheappropriatetextfieldsandthenclickNext.

http://www.javacodegeeks.com/2013/10/androidheaderandfooterlayoutexample.html

1/9

12/30/2014

AndroidHeaderandFooterlayoutexample|JavaCodeGeeks

InthenextwindowmakesuretheCreateactivityoptionisselectedinordertocreateanewactivityforyourproject,andclickNext.
Thisisoptionalasyoucancreateanewactivityaftercreatingtheproject,butyoucandoitallinonestep.

SelectBlankActivityandclickNext.

Youwillbeaskedtospecifysomeinformationaboutthenewactivity.IntheLayoutNametextfieldyouhavetospecifythenameofthe
filethatwillcontainthelayoutdescriptionofyourapp.Inourcasethefile res/layout/main.xml willbecreated.Then,clickFinish.

2.CreatingthelayoutoftheMainActivity
Open res/layout/main.xml file:

http://www.javacodegeeks.com/2013/10/androidheaderandfooterlayoutexample.html

2/9

12/30/2014

AndroidHeaderandFooterlayoutexample|JavaCodeGeeks

Andpastethefollowingcode:
main.xml:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

<?xmlversion="1.0"encoding="utf8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!Headeralignedtotop>

<RelativeLayout
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#FC9"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="FixedHeader"
android:textColor="#000"
android:textSize="20sp"/>
</RelativeLayout>

<!Footeralignedtobottom>

<RelativeLayout
android:id="@+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#FC0"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="FixedFooter"
android:textColor="#000"
android:textSize="20sp"/>
</RelativeLayout>

<!Contentbelowheaderandabovefooter>

<RelativeLayout
android:id="@+id/content"
android:layout_width="fill_parent"

50
51
52
53
54
55
56
57
58
59
60
61
62
63

android:layout_height="fill_parent"
android:layout_above="@id/footer"
android:layout_below="@id/header"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Content"
android:textColor="#33E"
android:textSize="20sp"/>
</RelativeLayout>

</RelativeLayout>

Theideahereisverysimple.Wehavetwo RelativeLayouts ,onealignedatthetopofthescreen,


using android:layout_alignParentTop="true" property,andonealignedatthebottomofthescreen
using android:layout_alignParentBottom="true" property.Thenwesimplyplacea RelativeLayout betweenthesetwoview
using android:layout_above="@id/footer" and android:layout_below="@id/header" .Thesepropertieswillplace
our RelativeLayout withid content ,representingthecontentareaofourLayout,abovetheelementwithid footer andbellowthe
elementwithid header .
http://www.javacodegeeks.com/2013/10/androidheaderandfooterlayoutexample.html

3/9

12/30/2014

AndroidHeaderandFooterlayoutexample|JavaCodeGeeks

YoucanpreviewthelayoutyouvecreatedintheGraphicalLayouteditor:

2.CodetheMainActivity
UsethePackageExplorertonavigatetotheJavafileoftheActivityyouvecreated:

Forthisexampleyoudonthavetochangeanythingtotheautogeneratedcodesoyoucanleaveitasitis.
MainActivity.java:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21

packagecom.javacodegeeks.android.androidlayoutsexample;

importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.view.Menu;

publicclassMainActivityextendsActivity{

@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

@Override
publicbooleanonCreateOptionsMenu(Menumenu){
//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
}
}

4.Runtheapplication
ThisishowourLayoutlooksontheemulator:

http://www.javacodegeeks.com/2013/10/androidheaderandfooterlayoutexample.html

4/9

12/30/2014

AndroidHeaderandFooterlayoutexample|JavaCodeGeeks

androidemulator

MakingyourLayoutflexible
Intheabovecodewesortofhardcodedeverythinginthemainlayoutoftheactivity.Butyoumaywanttoinflatethecontentsofeach
layoutdynamicallyinyourcode.Or,moreimportantlyyoumaywanttomakethislayoutreusabletoyourotheractivities,eachone
havingtheirowncontentstodisplayandmaybetheirownheadersandfooters.
Toachievethat,wearesimplygoingtoseparateeverycomponentfromtheother.Wearegoingtocreatetheheaderlayouttoa
differentXMLfileanddothesameforthefooter.Now,everyactivitythathasitsowncontentcanincludetheheaderandthefooterin
theirownLayouts.
TocreateanewXMLLayoutfilecontainingtheitemsyouwanttofillyour ScrollView with.Tocreateanewlayoutfile,gotothe
PackageExplorerandfind /res/layout folder.RightClickonthefolder>New>Other>Android>AndroidXMLLayoutfile:
newlayoutfile

Putanameforyournewlayoutfile,andselectRelativeLayoutfromthelist(althoughthisisnotabsolutelynecessary)andclickFinish:

http://www.javacodegeeks.com/2013/10/androidheaderandfooterlayoutexample.html

5/9

12/30/2014

AndroidHeaderandFooterlayoutexample|JavaCodeGeeks

headerxml

Youneedtocreate footer.xml also.


So,afterthecreationofthenewlayoutXMLfiles,thisisthenewProjectStructure:
newprojectstructure

header.xml
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16

<RelativeLayout
android:id="@+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#FC0"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="FixedFooter"
android:textColor="#000"
android:textSize="20sp"/>
</RelativeLayout>

footer.xml
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17

<?xmlversion="1.0"encoding="utf8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#FC0"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="FixedFooter"
android:textColor="#000"
android:textSize="20sp"/>

http://www.javacodegeeks.com/2013/10/androidheaderandfooterlayoutexample.html

6/9

12/30/2014

18

AndroidHeaderandFooterlayoutexample|JavaCodeGeeks

</RelativeLayout>

main.xml
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

<?xmlversion="1.0"encoding="utf8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!Headeralignedtotop>

<includelayout="@layout/header"/>

<!Footeralignedtobottom>

<includelayout="@layout/footer"/>

<!Contentbelowheaderandabovefooter>

<RelativeLayout
android:id="@+id/content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@id/footer"
android:layout_below="@id/header"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Content"
android:textColor="#33E"
android:textSize="20sp"/>
</RelativeLayout>

</RelativeLayout>

AsyoucanseewevesimplyseparatedtheRelativeLayoutsoftheheaderandthefootertodifferentXMLfiles.Sonow,youcaninclude
theminanyLayoutyouwant.Youcandothatbywritting <includelayout="@layout/header"/> toincludetheheaderand <include
layout="@layout/footer"/> ( header and footer mustcorrespondtothenamesyougavetotherespectiveXMLLayoutfiles)

Runtheapplication
ThisishowourLayoutlooksontheemulator:
androidemulator

DownloadEclipseProject
ThiswasanAndroidexampleonhowtocreatefixedHeaderandFooterreusablelayouts.DownloadtheEclipseProjectofthis
tutorial:AndroidLayoutsExample.zip

DoyouwanttoknowhowtodevelopyourskillsettobecomeaJavaRockstar?
SubscribetoournewslettertostartRockingrightnow!
TogetyoustartedwegiveyoutwoofourbestsellingeBooksforFREE!

JPAMiniBook
LearnhowtoleveragethepowerofJPAinordertocreaterobustandflexibleJavaapplications.
WiththisMiniBook,youwillgetintroducedtoJPAandsmoothlytransitiontomoreadvanced
concepts.

JVMTroubleshootingGuide
TheJavavirtualmachineisreallythefoundationofanyJavaEEplatform.Learnhowtomasterit
withthisadvancedguide!

Emailaddress:

Youremailaddress

http://www.javacodegeeks.com/2013/10/androidheaderandfooterlayoutexample.html

Signup!

7/9

12/30/2014

AndroidHeaderandFooterlayoutexample|JavaCodeGeeks

5Responsesto"AndroidHeaderandFooterlayoutexample"

thinagaran
November6th,2013at8:29pm

Onanunrelatednote,didyoucompileusingJDK1.7
Reply

Joielechong
March27th,2014at7:00am

Thanksforthecode.:D
Reply

SohailMalik
April2nd,2014at11:03pm

Extremegoodjobdonebyyou.Iappreciateyourefforts,stayblessed.
Reply

JoanNbusoba
May13th,2014at12:24pm

Thanksalot.Ineededthisbutididntknowhowtodoit.Thanks!!
Reply

sarwesh
September4th,2014at4:22pm

Thanksforcode
Reply

LeaveaReply
Name(Required)
Mail(willnotbepublished)(Required)
Website

+1=five
Notifymeoffollowupcommentsviaemail.Youcanalsosubscribewithoutcommenting.
Signmeupforthenewsletter!
SubmitComment

KnowledgeBase

Academy

Partners

Mkyong

Examples
Resources
Tutorials
Whitepapers

TheCodeGeeksNetwork

HallOfFame

AboutJavaCodeGeeks

AndroidFullApplicationTutorialseries

JCGs(JavaCodeGeeks)isanindependentonlinecommunityfocusedon

GWT2Spring3JPA2Hibernate3.5Tutorial

creatingtheultimateJavatoJavadevelopersresourcecentertargetedatthe
technicalarchitect,technicalteamlead(seniordeveloper),projectmanagerand

AdvantagesandDisadvantagesofCloud

juniordevelopersalike.JCGsservetheJava,SOA,AgileandTelecom

JavaCodeGeeks

ComputingCloudcomputingprosandcons

communitieswithdailynewswrittenbydomainexperts,articles,tutorials,

.NETCodeGeeks

AndroidGoogleMapsTutorial

reviews,announcements,codesnippetsandopensourceprojects.

WebCodeGeeks

AndroidLocationBasedServicesApplication
GPSlocation
11OnlineLearningwebsitesthatyoushould
checkout
JavaBestPracticesVectorvsArrayListvs

http://www.javacodegeeks.com/2013/10/androidheaderandfooterlayoutexample.html

8/9

12/30/2014

AndroidHeaderandFooterlayoutexample|JavaCodeGeeks

HashSet
AndroidJSONParsingwithGsonTutorial
AndroidQuickPreferencesTutorial
DifferencebetweenComparatorand
ComparableinJava

JavaCodeGeeksandallcontentcopyright20102014,ExelixisMediaLtd|TermsofUse|PrivacyPolicy|Contact
AlltrademarksandregisteredtrademarksappearingonJavaCodeGeeksarethepropertyoftheirrespectiveowners.
JavaisatrademarkorregisteredtrademarkofOracleCorporationintheUnitedStatesandothercountries.
JavaCodeGeeksisnotconnectedtoOracleCorporationandisnotsponsoredbyOracleCorporation.

http://www.javacodegeeks.com/2013/10/androidheaderandfooterlayoutexample.html

9/9

Potrebbero piacerti anche