Start
Zufällige Seite
Anmelden
Einstellungen
Haftungsausschluss
Suchen
Übersetzungen exportieren
Übersetzen
Einstellungen
Gruppe
Android Training
Android Training/Building a Simple User Interface
Android Training/Building Your First App
Android Training/Creating an Android Project
Android Training/Managing the Activity Lifecycle
Android Training/Running Your Application
Android Training/Starting Another Activity
Android Training/Supporting different devices
Android Training/Supporting Different Languages
Android Training/Supporting Different Platform Versions
Android Training/Supporting Different Screens
Vorlage:Android Training/Attribution
Vorlage:Android Training/Content
Vorlage:Android Training/Inhalt/Building a Dynamic UI with Fragments
Vorlage:Android Training/Inhalt/Deine erste App
Vorlage:Android Training/Inhalt/Interacting with Other Apps
Vorlage:Android Training/Inhalt/Managing the Activity Lifecycle
Vorlage:Android Training/Inhalt/Saving Data
Vorlage:Android Training/Inhalt/Supporting different devices
Vorlage:Android Training/Inhalt/Working with System Permissions
Sprache
aa - Qafár af
aae - Arbërisht
ab - аԥсшәа
abs - bahasa ambon
ace - Acèh
acm - عراقي
ady - адыгабзэ
ady-cyrl - адыгабзэ
aeb - تونسي / Tûnsî
aeb-arab - تونسي
aeb-latn - Tûnsî
af - Afrikaans
aln - Gegë
alt - алтай тил
am - አማርኛ
ami - Pangcah
an - aragonés
ang - Ænglisc
ann - Obolo
anp - अंगिका
apc - شامي
ar - العربية
arc - ܐܪܡܝܐ
arn - mapudungun
arq - جازايرية
ary - الدارجة
arz - مصرى
as - অসমীয়া
ase - American sign language
ast - asturianu
atj - Atikamekw
av - авар
avk - Kotava
awa - अवधी
ay - Aymar aru
az - azərbaycanca
azb - تۆرکجه
ba - башҡортса
ban - Basa Bali
ban-bali - ᬩᬲᬩᬮᬶ
bar - Boarisch
bbc - Batak Toba
bbc-latn - Batak Toba
bcc - جهلسری بلوچی
bci - wawle
bcl - Bikol Central
bdr - Bajau Sama
be - беларуская
be-tarask - беларуская (тарашкевіца)
bew - Betawi
bg - български
bgn - روچ کپتین بلوچی
bh - भोजपुरी
bho - भोजपुरी
bi - Bislama
bjn - Banjar
blk - ပအိုဝ်ႏဘာႏသာႏ
bm - bamanankan
bn - বাংলা
bo - བོད་ཡིག
bpy - বিষ্ণুপ্রিয়া মণিপুরী
bqi - بختیاری
br - brezhoneg
brh - Bráhuí
bs - bosanski
btm - Batak Mandailing
bto - Iriga Bicolano
bug - Basa Ugi
bxr - буряад
ca - català
cbk-zam - Chavacano de Zamboanga
ccp - 𑄌𑄋𑄴𑄟𑄳𑄦
cdo - 閩東語 / Mìng-dĕ̤ng-ngṳ̄
ce - нохчийн
ceb - Cebuano
ch - Chamoru
chn - chinuk wawa
cho - Chahta anumpa
chr - ᏣᎳᎩ
chy - Tsetsêhestâhese
ckb - کوردی
co - corsu
cps - Capiceño
cpx - 莆仙語 / Pó-sing-gṳ̂
cpx-hans - 莆仙语(简体)
cpx-hant - 莆仙語(繁體)
cpx-latn - Pó-sing-gṳ̂ (Báⁿ-uā-ci̍)
cr - Nēhiyawēwin / ᓀᐦᐃᔭᐍᐏᐣ
crh - qırımtatarca
crh-cyrl - къырымтатарджа (Кирилл)
crh-latn - qırımtatarca (Latin)
crh-ro - tatarşa
cs - čeština
csb - kaszëbsczi
cu - словѣньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ
cv - чӑвашла
cy - Cymraeg
da - dansk
dag - dagbanli
de - Deutsch
de-at - Österreichisches Deutsch
de-ch - Schweizer Hochdeutsch
de-formal - Deutsch (Sie-Form)
dga - Dagaare
din - Thuɔŋjäŋ
diq - Zazaki
dsb - dolnoserbski
dtp - Dusun Bundu-liwan
dty - डोटेली
dv - ދިވެހިބަސް
dz - ཇོང་ཁ
ee - eʋegbe
efi - Efịk
egl - Emiliàn
el - Ελληνικά
eml - emiliàn e rumagnòl
en - English
en-ca - Canadian English
en-gb - British English
eo - Esperanto
es - español
es-419 - español de América Latina
es-formal - español (formal)
et - eesti
eu - euskara
ext - estremeñu
fa - فارسی
fat - mfantse
ff - Fulfulde
fi - suomi
fit - meänkieli
fj - Na Vosa Vakaviti
fo - føroyskt
fon - fɔ̀ngbè
fr - français
frc - français cadien
frp - arpetan
frr - Nordfriisk
fur - furlan
fy - Frysk
ga - Gaeilge
gaa - Ga
gag - Gagauz
gan - 贛語
gan-hans - 赣语(简体)
gan-hant - 贛語(繁體)
gcf - kréyòl Gwadloup
gcr - kriyòl gwiyannen
gd - Gàidhlig
gl - galego
gld - на̄ни
glk - گیلکی
gn - Avañe'ẽ
gom - गोंयची कोंकणी / Gõychi Konknni
gom-deva - गोंयची कोंकणी
gom-latn - Gõychi Konknni
gor - Bahasa Hulontalo
got - 𐌲𐌿𐍄𐌹𐍃𐌺
gpe - Ghanaian Pidgin
grc - Ἀρχαία ἑλληνικὴ
gsw - Alemannisch
gu - ગુજરાતી
guc - wayuunaiki
gur - farefare
guw - gungbe
gv - Gaelg
ha - Hausa
hak - 客家語/Hak-kâ-ngî
haw - Hawaiʻi
he - עברית
hi - हिन्दी
hif - Fiji Hindi
hif-latn - Fiji Hindi
hil - Ilonggo
hno - ہندکو
ho - Hiri Motu
hr - hrvatski
hrx - Hunsrik
hsb - hornjoserbsce
hsn - 湘语
ht - Kreyòl ayisyen
hu - magyar
hu-formal - magyar (formal)
hy - հայերեն
hyw - Արեւմտահայերէն
hz - Otsiherero
ia - interlingua
ibb - ibibio
id - Bahasa Indonesia
ie - Interlingue
ig - Igbo
igl - Igala
ii - ꆇꉙ
ik - Iñupiatun
ike-cans - ᐃᓄᒃᑎᑐᑦ
ike-latn - inuktitut
ilo - Ilokano
inh - гӀалгӀай
io - Ido
is - íslenska
it - italiano
iu - ᐃᓄᒃᑎᑐᑦ / inuktitut
ja - 日本語
jam - Patois
jbo - la .lojban.
jut - jysk
jv - Jawa
ka - ქართული
kaa - Qaraqalpaqsha
kab - Taqbaylit
kai - Karai-karai
kbd - адыгэбзэ
kbd-cyrl - адыгэбзэ
kbp - Kabɩyɛ
kcg - Tyap
kea - kabuverdianu
kg - Kongo
kge - Basa Kumoring
khw - کھوار
ki - Gĩkũyũ
kiu - Kırmancki
kj - Kwanyama
kjh - хакас
kjp - ဖၠုံလိက်
kk - қазақша
kk-arab - قازاقشا (تٴوتە)
kk-cn - قازاقشا (جۇنگو)
kk-cyrl - қазақша (кирил)
kk-kz - қазақша (Қазақстан)
kk-latn - qazaqşa (latın)
kk-tr - qazaqşa (Türkïya)
kl - kalaallisut
km - ភាសាខ្មែរ
kn - ಕನ್ನಡ
ko - 한국어
ko-kp - 조선말
koi - перем коми
kr - kanuri
krc - къарачай-малкъар
kri - Krio
krj - Kinaray-a
krl - karjal
ks - कॉशुर / کٲشُر
ks-arab - کٲشُر
ks-deva - कॉशुर
ksh - Ripoarisch
ksw - စှီၤ
ku - kurdî
ku-arab - کوردی (عەرەبی)
ku-latn - kurdî (latînî)
kum - къумукъ
kus - Kʋsaal
kv - коми
kw - kernowek
ky - кыргызча
la - Latina
lad - Ladino
lb - Lëtzebuergesch
lbe - лакку
lez - лезги
lfn - Lingua Franca Nova
lg - Luganda
li - Limburgs
lij - Ligure
liv - Līvõ kēļ
lki - لەکی
lld - Ladin
lmo - lombard
ln - lingála
lo - ລາວ
loz - Silozi
lrc - لۊری شومالی
lt - lietuvių
ltg - latgaļu
lus - Mizo ţawng
luz - لئری دوٙمینی
lv - latviešu
lzh - 文言
lzz - Lazuri
mad - Madhurâ
mag - मगही
mai - मैथिली
map-bms - Basa Banyumasan
mdf - мокшень
mg - Malagasy
mh - Ebon
mhr - олык марий
mi - Māori
min - Minangkabau
mk - македонски
ml - മലയാളം
mn - монгол
mnc - ᠮᠠᠨᠵᡠ ᡤᡳᠰᡠᠨ
mnc-latn - manju gisun
mnc-mong - ᠮᠠᠨᠵᡠ ᡤᡳᠰᡠᠨ
mni - ꯃꯤꯇꯩ ꯂꯣꯟ
mnw - ဘာသာမန်
mo - молдовеняскэ
mos - moore
mr - मराठी
mrh - Mara
mrj - кырык мары
ms - Bahasa Melayu
ms-arab - بهاس ملايو
mt - Malti
mui - Baso Palembang
mus - Mvskoke
mwl - Mirandés
my - မြန်မာဘာသာ
myv - эрзянь
mzn - مازِرونی
na - Dorerin Naoero
nah - Nāhuatl
nan - 閩南語 / Bân-lâm-gú
nan-hant - 閩南語(傳統漢字)
nap - Napulitano
nb - norsk bokmål
nds - Plattdüütsch
nds-nl - Nedersaksies
ne - नेपाली
new - नेपाल भाषा
ng - Oshiwambo
nia - Li Niha
nit - కొలామి
niu - Niuē
nl - Nederlands
nl-informal - Nederlands (informeel)
nmz - nawdm
nn - norsk nynorsk
no - norsk
nod - ᨣᩤᩴᨾᩮᩬᩥᨦ
nog - ногайша
nov - Novial
nqo - ߒߞߏ
nrm - Nouormand
nso - Sesotho sa Leboa
nv - Diné bizaad
ny - Chi-Chewa
nyn - runyankore
nyo - Orunyoro
nys - Nyunga
oc - occitan
ojb - Ojibwemowin
olo - livvinkarjala
om - Oromoo
or - ଓଡ଼ିଆ
os - ирон
pa - ਪੰਜਾਬੀ
pag - Pangasinan
pam - Kapampangan
pap - Papiamentu
pcd - Picard
pcm - Naijá
pdc - Deitsch
pdt - Plautdietsch
pfl - Pälzisch
pi - पालि
pih - Norfuk / Pitkern
pl - polski
pms - Piemontèis
pnb - پنجابی
pnt - Ποντιακά
prg - prūsiskan
ps - پښتو
pt - português
pt-br - português do Brasil
pwn - pinayuanan
qu - Runa Simi
qug - Runa shimi
rgn - Rumagnôl
rif - Tarifit
rki - ရခိုင်
rm - rumantsch
rmc - romaňi čhib
rmy - romani čhib
rn - ikirundi
ro - română
roa-tara - tarandíne
rsk - руски
ru - русский
rue - русиньскый
rup - armãneashti
ruq - Vlăheşte
ruq-cyrl - Влахесте
ruq-latn - Vlăheşte
rut - мыхаӀбишды
rw - Ikinyarwanda
ryu - うちなーぐち
sa - संस्कृतम्
sah - саха тыла
sat - ᱥᱟᱱᱛᱟᱲᱤ
sc - sardu
scn - sicilianu
sco - Scots
sd - سنڌي
sdc - Sassaresu
sdh - کوردی خوارگ
se - davvisámegiella
se-fi - davvisámegiella (Suoma bealde)
se-no - davvisámegiella (Norgga bealde)
se-se - davvisámegiella (Ruoŧa bealde)
sei - Cmique Itom
ses - Koyraboro Senni
sg - Sängö
sgs - žemaitėška
sh - srpskohrvatski / српскохрватски
sh-cyrl - српскохрватски (ћирилица)
sh-latn - srpskohrvatski (latinica)
shi - Taclḥit
shi-latn - Taclḥit
shi-tfng - ⵜⴰⵛⵍⵃⵉⵜ
shn - ၽႃႇသႃႇတႆး
shy - tacawit
shy-latn - tacawit
si - සිංහල
simple - Simple English
sjd - кӣллт са̄мь кӣлл
sje - bidumsámegiella
sk - slovenčina
skr - سرائیکی
skr-arab - سرائیکی
sl - slovenščina
sli - Schläsch
sm - Gagana Samoa
sma - åarjelsaemien
smn - anarâškielâ
sms - nuõrttsääʹmǩiõll
sn - chiShona
so - Soomaaliga
sq - shqip
sr - српски / srpski
sr-ec - српски (ћирилица)
sr-el - srpski (latinica)
srn - Sranantongo
sro - sardu campidanesu
ss - SiSwati
st - Sesotho
stq - Seeltersk
sty - себертатар
su - Sunda
sv - svenska
sw - Kiswahili
syl - ꠍꠤꠟꠐꠤ
szl - ślůnski
szy - Sakizaya
ta - தமிழ்
tay - Tayal
tcy - ತುಳು
tdd - ᥖᥭᥰᥖᥬᥳᥑᥨᥒᥰ
te - తెలుగు
tet - tetun
tg - тоҷикӣ
tg-cyrl - тоҷикӣ
tg-latn - tojikī
th - ไทย
ti - ትግርኛ
tk - Türkmençe
tl - Tagalog
tly - tolışi
tly-cyrl - толыши
tn - Setswana
to - lea faka-Tonga
tok - toki pona
tpi - Tok Pisin
tr - Türkçe
tru - Ṫuroyo
trv - Seediq
ts - Xitsonga
tt - татарча / tatarça
tt-cyrl - татарча
tt-latn - tatarça
ttj - Orutooro
tum - chiTumbuka
tw - Twi
ty - reo tahiti
tyv - тыва дыл
tzm - ⵜⴰⵎⴰⵣⵉⵖⵜ
udm - удмурт
ug - ئۇيغۇرچە / Uyghurche
ug-arab - ئۇيغۇرچە
ug-latn - Uyghurche
uk - українська
ur - اردو
uz - oʻzbekcha / ўзбекча
uz-cyrl - ўзбекча
uz-latn - oʻzbekcha
ve - Tshivenda
vec - vèneto
vep - vepsän kel’
vi - Tiếng Việt
vls - West-Vlams
vmf - Mainfränkisch
vmw - emakhuwa
vo - Volapük
vot - Vaďďa
vro - võro
wa - walon
wal - wolaytta
war - Winaray
wls - Fakaʻuvea
wo - Wolof
wuu - 吴语
wuu-hans - 吴语(简体)
wuu-hant - 吳語(正體)
xal - хальмг
xh - isiXhosa
xmf - მარგალური
xsy - saisiyat
yi - ייִדיש
yo - Yorùbá
yrl - Nhẽẽgatú
yue - 粵語
yue-hans - 粵语(简体)
yue-hant - 粵語(繁體)
za - Vahcuengh
zea - Zeêuws
zgh - ⵜⴰⵎⴰⵣⵉⵖⵜ ⵜⴰⵏⴰⵡⴰⵢⵜ
zgh-latn - tamaziɣt tanawayt
zh - 中文
zh-cn - 中文(中国大陆)
zh-hans - 中文(简体)
zh-hant - 中文(繁體)
zh-hk - 中文(香港)
zh-mo - 中文(澳門)
zh-my - 中文(马来西亚)
zh-sg - 中文(新加坡)
zh-tw - 中文(臺灣)
zu - isiZulu
Format
Für die Offline-Übersetzung exportieren
Im systemeigenen Format exportieren
Im CSV-Format exportieren
Hole
<languages /> After completing the [[Spezial:MyLanguage/Android Training/Building a Simple User Interface|previous lesson]], you have an app that shows an activity (a single screen) with a text field and a button. In this lesson, you’ll add some code to <code>MyActivity</code> that starts a new activity when the user clicks the Send button. == Respond to the Send Button == # In Android Studio, from the <code>res/layout</code> directory, edit the <code>content_my.xml</code> file. # Add the <code>[http://developer.android.com/reference/android/view/View.html#attr_android:onClick android:onClick]</code> attribute to the <code>[http://developer.android.com/reference/android/widget/Button.html <Button>]</code> element. #: ''res/layout/content_my.xml''<syntaxhighlight lang="java"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" android:onClick="sendMessage" /> </syntaxhighlight> #: The <code>android:onClick</code> attribute’s value, <code>"sendMessage"</code>, is the name of a method in your activity that the system calls when the user clicks the button. # In the <code>java/com.mycompany.myfirstapp</code> directory, open the <code>MyActivity.java</code> file. # Within the <code>MyActivity</code> class, add the <code>sendMessage()</code> method stub shown below. #: ''java/com.mycompany.myfirstapp/MyActivity.java''<syntaxhighlight lang="java"> /** Called when the user clicks the Send button */ public void sendMessage(View view) { // Do something in response to button } </syntaxhighlight> #: In order for the system to match this method to the method name given to <code>android:onClick</code>, the signature must be exactly as shown. Specifically, the method must: #* Be public #* Have a void return value #* Have a <code>[http://developer.android.com/reference/android/view/View.html View]</code> as the only parameter (this will be the <code>View</code> that was clicked) Next, you’ll fill in this method to read the contents of the text field and deliver that text to another activity. == Build an Intent == # In <code>MyActivity.java</code>, inside the <code>sendMessage()</code> method, create an <code>Intent</code> to start an activity called <code>DisplayMessageActivity</code> with the following code: #: ''java/com.mycompany.myfirstapp/MyActivity.java''<syntaxhighlight lang="java"> public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.class); } </syntaxhighlight> #: '''Note:''' The reference to <code>DisplayMessageActivity</code> will raise an error if you’re using an IDE such as Android Studio because the class doesn’t exist yet. Ignore the error for now; you’ll create the class soon. The constructor used here takes two parameters: #* A <code>Context</code> as its first parameter (<code>this</code> is used because the <code>Activity</code> class is a subclass of <code>Context</code>) #* The <code>Class</code> of the app component to which the system should deliver the <code>Intent</code> (in this case, the activity that should be started) Android Studio indicates that you must import the <code>Intent</code> class. # At the top of the file, import the <code>Intent</code> class: #: ''java/com.mycompany.myfirstapp/MyActivity.java''<syntaxhighlight lang="java"> import android.content.Intent; </syntaxhighlight> #: '''Tip:''' In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes. # Inside the <code>sendMessage()</code> method, use <code>findViewById()</code> to get the <code>EditText</code> element. #: ''java/com.mycompany.myfirstapp/MyActivity.java''<syntaxhighlight lang="java"> public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(R.id.edit_message); } </syntaxhighlight> # At the top of the file, import the <code>EditText</code> class. In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes. # Assign the text to a local <code>message</code> variable, and use the <code>putExtra()</code> method to add its text value to the intent. #: ''java/com.mycompany.myfirstapp/MyActivity.java''<syntaxhighlight lang="java"> public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); } </syntaxhighlight> #: An <code>Intent</code> can carry data types as key-value pairs called ''extras''. The <code>putExtra()</code> method takes the key name in the first parameter and the value in the second parameter. # At the top of the <code>MyActivity</code> class, add the <code>EXTRA_MESSAGE</code> definition as follows: #: ''java/com.mycompany.myfirstapp/MyActivity.java''<syntaxhighlight lang="java"> public class MyActivity extends AppCompatActivity { public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE"; ... } </syntaxhighlight> #: For the next activity to query the extra data, you should define the key for your intent's extra using a public constant. It's generally a good practice to define keys for intent extras using your app's package name as a prefix. This ensures the keys are unique, in case your app interacts with other apps. # In the <code>sendMessage()</code> method, to finish the intent, call the <code>startActivity()</code> method, passing it the <code>Intent</code> object created in step 1. With this new code, the complete <code>sendMessage()</code> method that's invoked by the Send button now looks like this: ''java/com.mycompany.myfirstapp/MyActivity.java''<syntaxhighlight lang="java"> /** Called when the user clicks the Send button */ public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); } </syntaxhighlight> The system receives this call and starts an instance of the <code>Activity</code> specified by the <code>Intent</code>. Now you need to create the <code>DisplayMessageActivity</code> class in order for this to work. == Create the Second Activity == All subclasses of <code>[http://developer.android.com/reference/android/app/Activity.html Activity]</code> must implement the <code>[http://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle) onCreate()]</code> method. This method is where the activity receives the intent with the message, then renders the message. Also, the <code>onCreate()</code> method must define the activity layout with the <code>setContentView()</code> method. This is where the activity performs the initial setup of the activity components. === Create a new activity using Android Studio === Android Studio includes a stub for the <code>onCreate()</code> method when you create a new activity. The ''New Android Activity'' window appears. # In Android Studio, in the <code>java</code> directory, select the package, '''com.mycompany.myfirstapp''', right-click, and select '''New > Activity > Blank Activity'''. # In the '''Choose options''' window, fill in the activity details: #* '''Activity Name''': DisplayMessageActivity #* '''Layout Name''': activity_display_message #* '''Title''': My Message #* '''Hierarchical Parent''': com.mycompany.myfirstapp.MyActivity #* '''Package name''': com.mycompany.myfirstapp Click '''Finish'''. # Open the <code>DisplayMessageActivity.java</code> file. The class already includes an implementation of the required <code>onCreate()</code> method. You update the implementation of this method later. If you're developing with Android Studio, you can run the app now, but not much happens. Clicking the Send button starts the second activity, but it uses a default "Hello world" layout provided by the template. You'll soon update the activity to instead display a custom text view. === Create the activity without Android Studio === If you're using a different IDE or the command line tools, do the following: # Create a new file named <code>DisplayMessageActivity.java</code> in the project's <code>src/</code> directory, next to the original<code>MyActivity.java</code> file. # Add the following code to the file: #: <syntaxhighlight lang="java"> public class DisplayMessageActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_message); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle app bar item clicks here. The app bar // automatically handles clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_display_message, container, false); return rootView; } } } </syntaxhighlight> #: '''Note:''' If you are using an IDE other than Android Studio, your project does not contain the <code>activity_display_message</code> layout that's requested by <code>[http://developer.android.com/reference/android/app/Activity.html#setContentView(android.view.View) setContentView()]</code>. That's OK because you will update this method later and won't be using that layout. # To your <code>strings.xml</code> file, add the new activity's title as follows: #: <syntaxhighlight lang="xml"> <resources> ... <string name="title_activity_display_message">My Message</string> </resources> </syntaxhighlight> # In your manifest file, <code>AndroidManifest.xml</code>, within the <code>Application</code> element, add the <code>[http://developer.android.com/guide/topics/manifest/activity-element.html <activity>]</code> element for your <code>DisplayMessageActivity</code> class, as follows: #: <syntaxhighlight lang="xml"> <application ... > ... <activity android:name="com.mycompany.myfirstapp.DisplayMessageActivity" android:label="@string/title_activity_display_message" android:parentActivityName="com.mycompany.myfirstapp.MyActivity" > <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.mycompany.myfirstapp.MyActivity" /> </activity> </application> </syntaxhighlight> The <code>[http://developer.android.com/guide/topics/manifest/activity-element.html#parent android:parentActivityName]</code> attribute declares the name of this activity's parent activity within the app's logical hierarchy. The system uses this value to implement default navigation behaviors, such as Up navigationon Android 4.1 (API level 16) and higher. You can provide the same navigation behaviors for older versions of Android by using the [http://developer.android.com/tools/support-library/index.html Support Library] and adding the <code>[http://developer.android.com/guide/topics/manifest/meta-data-element.html <meta-data>]</code> element as shown here. '''Note:''' Your Android SDK should already include the latest Android Support Library, which you installed during the [http://developer.android.com/sdk/installing/adding-packages.html Adding SDK Packages] step. When using the templates in Android Studio, the Support Library is automatically added to your app project (you can see the library's JAR file listed under ''Android Dependencies''). If you're not using Android Studio, you need to manually add the library to your project—follow the guide for [http://developer.android.com/tools/support-library/setup.html setting up the Support Library] then return here. If you're using a different IDE than Android Studio, don't worry that the app won't yet compile. You'll soon update the activity to display a custom text view. == Receive the Intent == Every <code>Activity</code> is invoked by an <code>[[Intent]]</code>, regardless of how the user navigated there. You can get the <code>Intent</code>that started your activity by calling <code>[http://developer.android.com/reference/android/app/Activity.html#getIntent() getIntent()]</code> and retrieve the data contained within the intent. # In the <code>java/com.mycompany.myfirstapp</code> directory, edit the <code>DisplayMessageActivity.java</code> file. # Get the intent and assign it to a local variable. #: <syntaxhighlight lang="java"> Intent intent = getIntent(); </syntaxhighlight> # At the top of the file, import the <code>[http://developer.android.com/reference/android/content/Intent.html Intent]</code> class. In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes. # Extract the message delivered by <code>MyActivity</code> with the <code>[http://developer.android.com/reference/android/content/Intent.html#getStringExtra(java.lang.String) getStringExtra()]</code> method. #: <syntaxhighlight lang="java"> String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE); </syntaxhighlight> == Display the Message == # In the res/layout directory, edit the <code>content_display_message.xml</code> file. # Add an <code>android:id</code> attribute to the <code>RelativeLayout</code>. You need this attribute to reference the object from your app code. #: <syntaxhighlight lang="xml"> < RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" ... android:id="@+id/content"> </RelativeLayout> </syntaxhighlight> # Switch back to editing <code>DisplayMessageActivity.java</code>. # In the <code>onCreate()</code> method, create a <code>TextView</code> object. #: <syntaxhighlight lang="java"> TextView textView = new TextView(this); </syntaxhighlight> # Set the text size and message with <code>[http://developer.android.com/reference/android/widget/TextView.html#setText(char[], int, int) setText()]</code>. #: <syntaxhighlight lang="java"> textView.setTextSize(40); textView.setText(message); </syntaxhighlight> # Add the <code>TextView</code> to the <code>[http://developer.android.com/reference/android/widget/RelativeLayout.html RelativeLayout]</code> identified by <code>R.id.content</code>. #: <syntaxhighlight lang="java"> RelativeLayout layout = (RelativeLayout) findViewById(R.id.content); layout.addView(textView); </syntaxhighlight> # At the top of the file, import the <code>[http://developer.android.com/reference/android/widget/TextView.html TextView]</code> class. In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes. The complete <code>onCreate()</code> method for <code>DisplayMessageActivity</code> now looks like this: <syntaxhighlight lang="java"> @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_message); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null) .show(); } }); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Intent intent = getIntent(); String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE); TextView textView = new TextView(this); textView.setTextSize(40); textView.setText(message); RelativeLayout layout = (RelativeLayout) findViewById(R.id.content); layout.addView(textView); </syntaxhighlight> You can now run the app. When it opens, type a message in the text field, and click '''Send'''. The second activity replaces the first one on the screen, showing the message you entered in the first activity. That's it, you've built your first Android app! {{TNT|Android_Training/Attribution}}