This app creates the same
RelativeLayout
and
Button
as the
activity_main.xml
of
Click Listener.
But this time the objects are created by Java,
not by an
.xml
file.
Our
activity_main.xml
is ignored and could have been deleted from this project.
The advantage of creating the user interface programmatically
is that we can have
if
statements that do different things under different conditions.
The first argument of the constructor
RelativeLayout
,
the constructor
Button
,
and the method
Toast.makeText
must be a
Context
object.
Fortunately, our
Activity
object is a
Context
object.
MainActivity.java
creates the
RelativeLayout
and the
Button
.
Don’t forget to call
addView
.
It also creates the
listener.
I commented out the first call to
setContentView
(which was written by Android Studio)
and replaced it with a call to another method with the same name.
activity_main.xml
:
unused and ignored,
because we commented out the
setContentView(R.layout.activity_main)
in
onCreate
.
strings.xml
dimens.xml
.
This file is created automatically by Android Studio and contains
dimension
resources.
Integers representing these values appear in
R.java
.
R.java
AndroidManifest.xml
build.gradle
(Module: app)
"Press in case of emergency."
,
etc.,
in
MainActivity.java
,
write them as
string
resources
in
strings.xml
.
<string name="button_text">Press in case of emergency.</string>
button.setText(R.string.button_text);