Kotlin.and.Android
Kotlin.and.Android
The Language
Choice
With the arrival of Android Studio 3 you
currently have a decision of programming in
Java or Kotlin. The benefit of Java is that it is
a notable and all around upheld language. To
obtain the ability then you likely could be in
an ideal situation beginning with Android
Programming In Java: Starting with an App
ISBN: 978-1871962550
Kotlin might be a be another dialect yet it is
now all around upheld for the straightforward
explanation that it is 100% viable with Java.
The Android libraries are totally written in
Java, however Kotlin can utilize them
without any issues. It is this that makes
Kotlin Android improvement conceivable.
Likewise, you’re not limited to Kotlin in a
venture. You can add Java code to your new
Kotlin venture and you can add Kotlin code
to a current Java project.
Put essentially, there is next to no danger
implied in moving to Kotlin and there is a
great deal to be acquired. Kotlin is a lot less
difficult and cleaner language than Java. It
has had the advantage of perceiving how Java
developed and keeping away from those slip-
ups. Kotlin endeavors to cut to the chase. In
Java you will more often than not think of
some code over and throughout and it very
well may be tedious and conceals the
effortlessness of what you are attempting to
do. At whatever point this happens Kotlin
changes the language with the goal that you
can communicate what you are doing
compactly. Software engineers moving from
Java to Kotlin by and large see that they like
this is on the grounds that they completely
finish less composing.Developers who just
realize Kotlin don’t have the foggiest idea
how fortunate they are!
Kotlin does things another way from Java and
keeping in mind that you can get the language
as you go you may jump at the chance to
peruse Programmer’s Guide To Kotlin
ISBN:978-1871962536.It isn’t required, as
long as you probably are aware Java or
another item situated language, you can get
Kotlin as you foster your Android
applications however I suggest learning the
better places of the language sometime. It
pays off to know your language.
The manner in which Kotlin is utilized and
the manners in which it changes Android
programming specifically are presented as we
come. In any case, the last section is a
concise gander at the significant impacts of
Kotlin on Android programming. If you want
a quick overview before you start then read
the final chapter, but in many ways it makes
moresense to read itas a summary after you
have encountered the ideas incontext.
Most importantly, except if you have a
promise to Java, you likely should begin new
undertakings in Kotlin and convert existing
tasks to Kotlin a cycle at a time.
Making a Start
I ’m not going to invest a ton of energy
disclosing how to introduce Android Studio
in a bit by bit manner as the Android site
works effectively and it is bound to be
exceptional. It is worth, nonetheless, going
over the fundamental principles.
https://developer.android.com/studio/
The installer will download all that you really
want including the JDK. Windows:
anewAndroidStudioproject
First Look
When everything is prepared you will see
Android Studio for the first time. As long as
everything has worked you ought to
ultimately, it requires around three minutes or
more, be given a perspective on your new
undertaking getting going in the Layout
Editor:
Problems?
If you get any mistake messages then the
odds are good that your venture hasn’t got
done with being handled. Trust that the
movement will stop. Assuming that you
check out the status line at the lower part of
the window you will see a message
saying“Gradle Build Finished” when Android
Studio has wrapped up with your new project.
If you actually have issues it merits
attempting the File,Invalidate Caches/Restart
order. This normally works for“Missing
styles” and comparable errors.
The IDE
Although there resembles a ton to dominate
in Android Studio ’s UI, the majority of it
you will just visit at times. The vital things to
see are that moving from left to right you
have:
☐ The Project window
☐ The instrument Palette and the Component
Tree window ☐ The Layout Editor
☐ The Attributes window
Basic Project
Structure
When the venture has wrapped up building
each of the records made can be seen by
opening the Projects tab. The most
compelling thing to see is that there are a
large number of organizers and files:
Anatomy of an
Activity
An Android application is comprised of at
least one Activity classes. You can consider
an Activity being something like a page total
with HTML to figure out what showcases and
JavaScript to figure out what it does. For the
situation of an Activity the format is
controlled by the XML record in asset (res)
organizer, this is frequently called the View,
and the conduct is dictated by the Kotlin or
Java code in the java folder.
The XML can be considered as a markup
language similar as HTML or
XAML. It characterizes an underlying format
for the screen when the application first runs.
It is feasible to produce new format parts at
runtime from the Java record. Truth be told,
assuming you truly need to, you can get rid of
the XML record and produce everything from
code, yet as you will find the XML markup
approach is a lot of the most ideal way to do
the occupation as a result of the accessibility
of the Layout Editor.
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width=“match_parent” android:layout_height=“match_pare
nt”
app:layout_behavior=“@string/appb ar_scrolling_view_behavior”
tools:context=“com.example.mikejames.helloworld1.MainActivity”
tools:showIn=“@layout/activity_main”>
<TextView
android:layout_width=“wrap_ content”
android:layout_height=“wr ap_content”
android:text=“Hello World!” app:layout_constraintBotto
m_toBottomOf=“parent” app:layout_constraintLeft_ toLeftOf=“parent”
app:layout_constraintRight _toRightOf=“parent” app:layout_constraintTop_
toTopOf=“parent”/>
</android.support.constraint.ConstraintLayout>
The Kotlin
If you double tap on the MainActivity .kt
document, or select the MainActivity.kt tab, you will see the
code it contains.A portion of the code may be
covered up however you can investigate it to
by tapping the + button to grow it.
Summary
☐ Android Studio makes making Android
applications significantly more
straightforward than different methodologies
and it is presently the main authority method
for doing the job.
☐ An application has somewhere around one
Activity and this characterizes a screen
format, the View, and a conduct. An Activity
doesn’t must have a UI, however much of the
time it has one.
Chapter 2
Activity and User
Interface
So you know how to make an Android
application, yet do you truly know how it
functions? In this section we check out how
to make a (UI) and how to attach it to the
code in the Activity.
We found in Chapter 1 how to utilize
Android Studio to construct the most
straightforward application. In transit we
found that an Android application comprises
of two sections– an Activity and a View. The
Activity is the code that accomplishes
something and the View gives the (UI). You
can consider this duality being like the
HTML page and the JavaScript that rushes to
cause it to accomplish something, or as a
XAML structure and the code behind.
The key thought is that an Activity is the
code that works with a UI screen
characterized by the View. This isn’t exactly
precise in that an Activity can change its view
so one piece of code can uphold various
perspectives. In any case, there are benefits to
utilizing one Activity for each view in light of
the fact that,for instance, this how the
Android back button explores your
application– from Activity to Activity. A
complex application almost consistently
comprises of numerous Activities that the
client can move between like pages yet a
straightforward application can oversee very
well with only one Activity. There is no rigid
guideline regarding the number of Activities
your application must have, yet it must have
least one.
If you are contemplating whether an Activity
can exist without a View the appropriate
response is that it can, yet it doesn’t check out
as this would pass on the client with no real
way to cooperate with your application.
Exercises are dynamic when their View is
introduced to the user. It truly is an
extraordinary improvement to think as far as
an Activity as a solitary screen with a client
interface.
If you need something to run without a UI
then what you need is an assistance or a
substance supplier which is past the extent of
this book. It is also worth making clear at this
early stage that an Activity has only one
thread of execution– the UI thread – and you
need to be careful not to perform any long
running task because this would block the UI
and make your app seem to freeze. That is, an
Activity can just do each thing in turn and
this incorporates cooperating with the client.
Assuming you compose a program utilizing a
solitary action and it does a confounded
estimation when the client clicks a
The MainActivity
There is one movement in each undertaking
that is assigned as the one to be dispatched
when your application begins. Assuming you
use Android Studio to make another Basic
Activity application called SimpleButton and
acknowledge every one of the defaults, the
startup Activity is called MainActivity of
course. You can change which Activity
begins the application by changing a line in
the application’s manifest.
The Manifest is a project file we haven't
discussed before because if you are using
Android Studio you can mostly ignore it and
allow Android Studio to construct and
maintain it for you, but it is better if you
know it exists and whatitdoes.
The Manifest is put away in the
application/shows registry
and is called AndroidManifest.xml.
It is a XML record that tells the Android
framework all that it has to know about your
application, including what authorization it
needs to run on a device.
Specifically it records the exercises as a
whole and which one is the one to use to
begin the app.
If you open the produced Manifest, by double
tapping on it, you will see somewhat way
down the file:
<activity android:name=“.MainActivity”
android:label=“SimpleButton” >
This characterizes the Activity the framework
has made for yourself and the lines just
underneath this characterize it as the startup
Activity:
<intent-filter>
<action android:name=“android.intent.action.MAIN”/>
<category android:name=“android.intent.category.LAUNCHER”/>
</purpose filter>
</activity>
Notice that the choice of which Activity starts
the app has nothing to do with what you call
it, i.e. calling it MainActivity isn't enough.
For the second you can depend on Android
Studio to care for the Manifest for you. Much
of the time you will possibly have to alter it
straightforwardly when you really want to
address a blunder or add something
advanced.
☐ onCreate
☐ onCreateOptionsMenu
☐ onOptionsItemSelected
View and
ViewGroup
So far so great, however it is critical to
understand that what occurs next it that the
XML record is delivered as a bunch of View
objects. That is, Java protests that are largely
sub-classes of the View object. The whole UI
and illustrations framework is executed as a
pecking order of parts got from the View
class.
}
Now if you run the program you will see the
button’s caption change when you click the
button.
This is a common pattern in making your UI
work – event handlers change the properties
of View objects to modify the UI.
Notice that this approach only works if you
know the type of the object that caused the
event and called the event handler. If your
event handler is
}
Notice that the button variable is a local
variable that hides the button property that
Kotlin automatically created for you from the
XML ids.
Summary
☐ An Activity is the unit of the Android app
and it roughly corresponds to one screenful of
user interface plus the code to make it work.
☐ In most cases you will create an Activity
for each UI screen you want to present to
your user.
☐ Only one Activity from your app is
running at any given time. ☐ An Activity is
single-threaded and runs on the UI thread. ☐
You can set which Activity starts the app in
the Manifest. Android Studio sets this to
MainActivity by default.
Chapter 3
Building a Simple UI
By this point in you understand how the
Activity and the View fit together to create a
simple application, but the Android UI is
more complicated than most because of its
need to cope with a range of very different
screen sizes and orientations. In this chapter
we look at the problem of layout and working
with the UI framework and on the way we’ll
build a calculator app.
When building an Android app you will
spend far more time than you could possibly
imagine on perfecting the UI. So it is
important that you master the basics so that
you can move on to code that does more
interesting things.
The learning curve with any UI framework is
more or less the same. First you have to find
out what constitutes an application that you
can run i.e. where is the code? In Android’s
case this is an Activity.
Next you have to work out how UI
components are represented, how you can
create them and how to hook up the UI with
the code. In Android’s case this is a matter of
a hierarchy of View objects and hooking up
with the code is a matter of finding the
objects representing each UI component and
adding event handlers.
Once you have the basics you have to start
exploring what components you have been
provided with to build a UI. In general this
varies from the extremely simple - the
Button, for example - to almost complete
applications in themselves - the Listview, for
example. It would take a long time to master
all of them, but what most programmers do is
make sure that they can use the basic
components and then find out about the
bigger more sophisticated components when
needed. The good news is that once you
know how one component, even the simplest,
works then most of it generalizes to bigger
more complicated things.
We also have to worry about how to lay out
the UI – how to size and position sets of
components. Android is particularly
sophisticated in this respect because being a
mobile operating system it has to contend
with a wide range of screen sizes and even
orientation changes while an app is running.
This is not a simple topic and we will have to
consider it in more detail later, but for the
moment let’s just take a look at the easier
aspects of screen layout.
The Button an
Example
Where else should we start – the Button is
almost the“Hello World” of UI construction.
If you know how to work with a Button you
are well on your way to understanding all of
the possible components. The good news is
that we have already met and used the Button
in Chapter 2 and discovered how to work
with it in code. However, there is still a lot to
find out.
Generally there are three things you need to
discover about using any component.
1. How to make it initially look like you want
it to. This is a matter of
Positioning– the
ConstraintLayout
Before you continue with the project select
and delete the default “hello world” text– it
makes trying things out easier to have a clean
design surface.
There are two views of your layout you can
opt for– design and blueprint. The design
view looks like your UI when it runs on a real
device. It is useful for getting an overall feel
and impression of what the UI really looks
like. The blueprint view shows you the UI in
skeleton form. This makes it quicker and
easier to work with when you are positioning
things. You can view both at the same time
but this is mostly a waste of screen space.
Some users prefer the blueprint view because
it seems to be light weight others prefer the
design view because it is complete. Use
whichever you find workable but there is no
doubt that the blueprint view is faster and
suffers from less lag as you try to position
components.
Next click on the Button in the palette and
drag it onto the layout.
Top
which gives the distance from the top edge
and
Contraints
top_toTopOf
which specifies the object that the positioning
is
relative to. If you look in the XML file you
will see:
app:layout_constraintTop_toTopOf=“parent”
android:layout_marginTop=“348dp”
Sizing
In comparison to positioning, sizing a
component is almost trivial. All components
have a Height and Width property and these
correspond to their drawn height and width
when the component is actually rendered on
the screen.
You may have noticed that there are what
look like sizing handles in the corners of the
components that you place in the Layout
Editor. If you drag any of these, the
component will change its size. However, the
components content will not be resized. All
that happens is that the content has some
space around it.If the content gets bigger or
smaller the component stays the same size.If
the content it too big then it won’t fit in the
component.
You can see the space is fixed in the
Attributes window. The lines shown
insidethecomponentrelatetothesizeofthecomponentanditsre
its content. Straight lines indicate a fixed size:
A Simple Button
Example – Baseline
Alignment
As a simple demonstration let ’s first place a
Button on the Layout Editor and use the Infer
Constraints button to apply some constraints.
If you find it difficult get a rough position
and then enter the exact margins then always
remember that you can move to the Attributes
window and enter them directly.
Next place a TextView widget on the Layout
Editor.
In this case the alignment we want is for the
text to be on the same line as the text in the
Button. This is a baseline alignment and one
of the more sophisticated alignments but if
you have the Layout Editor zoomed so that
you can see the full area of the screen the
chances are all you will be able to do is align
to the top or bottom of the Button.
If you look at the TextView’s representation
in the Layout Editor you will see that there
are two small icons below it. The first
removes all of the constraints from the
component, and the second makes the text
baseline, a small elliptical box, appear inside
it:
This represents the text in the TextView and
you can use it to set up a baseline constraint.
Orientation and
Resolution
One of the biggest challenges in creating apps
for Android is allowing for the range of
screen sizes and orientations. Mobile app
development is distinctly different from
desktop development because of this need to
deal with differing screen sizes. Even when
your app is running on a fixed device, the
user can still turn it though 90 degrees and
change the screen dimensions in a moment
and then turn it back again. So your app has
to respond to these changes. Fortunately
Android makes is easier for you by providing
facilities that specifically deal with resolution
and orientation changes, but you need to
come to terms with this situation as early as
possible in your progress to master Android
programming.
Code
So the code is decently easy.
We really want a private property to keep the
running all out in: hidden var complete = 0
Next we want an onButtonClick work which
will be utilized to deal with the onClick
occasion for the buttons in general.Allude
back to Chapter 2 assuming you don’t be
aware of straightforward occasion handling.
fun
onButtonClick
(v: View){ val
button=v as
Button
val
bText=button.text.toString()
val value=bText.toInt()
total+=value
textView.text= total.toString()
}
Put this code inside the MainActivity class as
one of its strategies, for instance right toward
the end not long before the last shutting }.
When you enter this code you will see a
considerable lot of the classes and techniques
in red:
This is on the grounds that they should be
imported to be utilized by the task. You can
do this physically, adding the essential import
articulations toward the beginning of the
record, however it is a lot more
straightforward to put the cursor into every
last one of the images in red and press
Alt+Enter and select Import Class if
fundamental. This ought to be turning out to
be natural by now.
Notice that the blunder hailed in textView
can’t be cleared– it is a genuine mistake. We
haven’t at this point characterized the UI and
textView doesn’t exist. It will once we make
the UI, so for the second overlook the error.
Layout
Now we direct our concentration toward the
design. Open the format document, erase the
default text and spot a solitary button on the
plan surface at the upper right of the screen
with a little space. We want to alter its text
characteristic and we can utilize an easy route
to get to it. Assuming that you double tap on
it you will be moved to the text property
window where you can enter 7 as its text
attribute.
While in the Attributes window observe the
onClick quality. Set this to onButtonClick,
the occasion overseer you have only written:
Summary
☐ You can make the XML design document
manually, however utilizing the Layout
Editor is easier.
☐ It is as yet helpful to know how the XML
record functions so you can alter it when the
Layout Editor lets you down in some way. ☐
The Layout Editor alters the manner in which
parts examine the Layout mode by changing
a part’s attributes.
☐ How you position a part relies upon the
Layout you are using. ☐ ConstraintLayout
allows you to situate parts comparative with
one another or to the container.
☐ The Layout Editor might change
numerous qualities to situate the part where
you need it.
☐ Use the Component Tree to choose parts
that are hard to choose in the Layout Editor.
☐ You can utilize the Attributes window to
choose and straightforwardly set any
attribute.
☐ If you see as situating or measuring
troublesome in the Layout Editor take a stab
at zooming in. ☐ You can utilize Android
Studio to see what your application resembles
on different screen sizes and orientations.
Chapter 4
Android Events
Working with Android Studio makes
assembling the UI simple with an intelligent
supervisor, yet you actually need to discover
how to deal with the things it isn’t exactly so
great at. We currently need to discover how
to function with any occasion, not simply
onClick. Despite the fact that most controls
can be utilized effectively utilizing only the
onClick occasion, there are different kinds of
occasion that can’t be dealt with basically by
setting an onEvent property in the Attribute
Window.
In this section we examine profundity at
Android occasion taking care of. As in the
past, the accentuation will be on utilizing
Android Studio and the Layout Editor to get
as a large part of the work done as possible.
Fortunately Kotlin’s help for passing
capacities as boundaries makes it all a lot
simpler. In any case, this doesn’t imply that
you can totally overlook the way that Java
handles the issue. Kotlin needs to work with
libraries written in Java and depend in transit
of executing occasion controllers.You don’t
need to dive excessively deep,however you
do have to know how Kotlin utilizes the Java
object-arranged occasion mechanism.
How Java Passes
Functions
If you would rather not know how things
work you can avoid this part until you stall
out with an occasion overseer and afterward
return and read it.
Events in Java are slightly more complicated
than other languages because originally
everything in Java was an object and the only
way a function can exist is as a method, i.e.
as part of an object. When you need to set up
an event handler you need to specify the
function to be called when the event happens.
Youcan’tpass a function as a parameter to
another function as Java
doesn’tsupportfunctiontypes.
The solution is to definean Interface that has
one abstract method–a SAM or Single
Abstract Method. The abstract method is the
function that will be used as the event
handler. To pass it you have to create an
instance of the Interface,i.e. an object that has
the method defined, and pass it.
Android Events
How occasions are executed in Android
observe a guideline pattern. Any item that can
produce an occasion will have a
seteventListener technique which can be
utilized to join an onEventListener item to the
occasion overseer list.
myMethod() {
. ..
}
}
. ..
}
The created
code is not difficult to understand:
object MyOnClick: View.OnClickListener { abrogate fun onClick(p0:
View?) {
TODO(“not implemented”)
}
}
The question mark toward the finish of View
is the main thing that may confound you.
This proclaims p0 to be a nullable kind. Java
doesn’t utilize Kotlin’s non-nullable sorts and
leads and thus anything passed into a Kotlin
work that is a Java object must be treated as a
nullable kind– subsequently the question
mark. It is great practice not to change
nullable sorts over to non-nullable sorts
without making sure that it isn’t really
invalid– see Chapter 17 for more information.
For this situation it is basically impossible
that that p0 can be invalid so we can project
it“dangerously” to Button which is non-
nullable:
object MyOnClick:View.OnClickListener{ supersede fun onClick(v:
View?) {
(v as Button).text = “You Clicked Me”
}
}
fun myMethod() {
. ..
}
}
onClick(p0: View?) {
(p0 as Button).text = “You Clicked Me”
}
})
Passing Functions In
Kotlin
We have examined the fundamental way of
passing an object that hosts event handlers as
methods, but there are three different,
althoughrelated, ways of passing an event
handler when the event object is a SAM, i.e.
only defines a single event handler:
Function References
Anonymous Functions
Lambda Expressions
Function References
Kotlin upholds capacities that don ’t have a
place with an article. Truth be told, the
adaptability of Kotlin’s way to deal with
capacities is one the purposes behind needing
to utilize it.
So in Kotlin it is entirely legitimate to write:
fun myFunction(){
…
}
That is:
myFunction()
is legal.
Kotlin additionally has a capacity reference
administrator :: which can be
}
then, at that point, you can write:
b.setOnClickListener(::clickEvent)
Anonymous
Functions
An unknown capacity is actually what its
name recommends – a capacity with no name
characterized. You basically write:
fun(parameters){body of function} You can store a
reference to a mysterious capacity in a
variable of the right kind and pass it to
another capacity.For example:
b.setOnClickListener(fun(v: View?) {
Events Using
Lambdas
To characterize an occasion overseer for an
occasion you should simply to utilize the
SetEventListener technique with a lambda as
its boundary. The lambda is the occasion
dealing with function.
For example:
button.setOnClickListener({ view - >
(view as Button).text = “You Clicked Me”
})
as the
{view - > (view as Button).text = “You Clicked Me”}
occasion overseer. Notice that you don’t need
to determine the sort of the boundary on the
grounds that the compiler can conclude it
from the kind of the boundary that the
setOnClickListener takes. There is one final
syntactic rearrangements. Assuming a
capacity
Closure
Closure is one of those themes that sounds as
though it will be troublesome. Lambda
articulations are not the same as most
capacities in that they approach each of the
factors that have a place with the strategy that
they are proclaimed in.
The way that the lambda approaches the
factors in the encasing technique has the
abnormal outcome that you could compose
the occasion controller as:
val message=“You Clicked Me”
This
button.setOnClickListener {view - > button.text = message}
might look odd however it works. Assuming
you don’t believe that it is odd then you
haven’t saw that the occasion overseer, the
lambda, will be executed when the Button is
clicked and this is probably going to be well
later the encasing strategy has gotten done
and every one of its factors not longer exist–
but the lambda can in any case utilize
message to set the Button’s text.
The framework will keep the worth of
message so the lambda can utilize it. This is
the pith of a conclusion – the protecting of
factors that have left extension so a lambda
can in any case get to them.
Unlike Java the factors caught by the Kotlin
conclusion don’t need to be final.
Notice that accessing message within the
lambda makes it look as if the lambda is
naturally still part of the code it is being
defined in and not a “detached”functional
entity that runs at some time in the distant
future– which is what it really is.
button.text = (++i).toString()
}
button.setOnClickListener(::eventHandler)
})
the capacity characterized in the article
approaches I by means of a closure. When
you initially meet the possibility of a
conclusion it can appear to be exceptionally
peculiar and surprisingly superfluous.
Nonetheless, when a capacity is characterized
inside a strategy the technique frames its
Using Breakpoints
The most straightforward method for making
sure that the occasion overseer is called is to
embed a breakpoint on the primary line of the
onClick method.
@Override
public void onClick(View view) { Button
b=(Button) view; b.setText(“you
clicked me”);
}
});
Summary
☐ In Java you can’t pass a capacity to set up
an occasion controller you need to pass an
item that contains the capacity as a method.
1. Function References
2. Anonymous Functions
3. Lambda Expressions
Chapter 5
Basic Controls
We have effectively utilized some UI controls
in past sections, yet presently we have found
how occasions work the time has come to
analyze how they work and how you can
change the way they look.
Buttons
Text Fields
Checkboxes
Radio Buttons
Toggle Buttons
Switches
The outcome is
two fastens that look something like:
You can invest a lot of energy investigating
ways of utilizing a button ’s ascribes to style
it similarly as you need it to look.
To join a tick occasion overseer on the two
buttons you can essentially characterize a
capacity in the Activity and set the onClick
property on each button. You can track down
instances of utilizing buttons this way in prior
chapters.
}
Notice that you currently need to supply the
kind of the boundary as the framework can’t
derive it. All that still needs to be done is to
set a case on each of the buttons:
button.setOnClickListener(myOnClickListener)
imageButton.setOnClickListener(myOnClickListener)
All Attributes
If you have checked out any instance of
utilizing Buttons in the
documentation, or then again on the off
chance that you take a gander at marginally
more seasoned Android code, you might find
a few ascribes that you can’t get to utilizing
Android Studio. This is on the grounds that
the Attributes window just shows you the
most utilized traits. To see them all you really
want to tap as soon as possible bolt symbol at
the top or lower part of the window.
drawableLeft
drawableRight
drawableStart
drawableEnd
drawableBottom
drawableTop
The onEditorAction
Event
Returning to the EditText control, how about
we add an overseer for the Send button. This
gives one more freedom to an illustration of
the overall course of adding an occasion
handler.
First spot an EditText for an email on the
plan surface and utilize the Attributes
window as depicted in the last area to add a
Send button to the IME that springs up when
the client enters message, that is track down
imeOptions and select actionSend.
Before you can deal with any new occasion
you need to find the name of the occasion
audience interface and the setOn technique
for that occasion. For the EditorAction
occasion the audience interface is called
OnEditorActionListener and the setOn
strategy is setOnEditorActionListener. With
this data we can continue as in the past and
utilize a lambda to execute the occasion
controller. For this situation we should do the
occupation inside the
setOnEditorActionListener as the occasion
overseer may be required by this one control:
editText.setOnEditorActionListener {v, actionId, occasion >
TextView textView,
int i,
KeyEvent keyEvent)
textView.text = editText.text }
true
}
Notice the utilization of the EditorInfo static
class to get the whole number id comparing
to the send activity. The EditorInfo class has
heaps of valuable constants and methods.
If you run the application you will find that
you can enter an email address into the
EditText field with the assistance of the
console and when you press the Send button
the location is moved to the TextView.
CheckBoxes
A CheckBox is a genuinely clear UI
component. It shows a little name,
constrained by the text property with or
without a tick mark close to it. The client can
choose or deselect as numerous checkboxes
as desired. In many cases you try not to
manage the condition of a CheckBox until the
client squeezes another control,generally a
major button stamped Done or comparative.
Then you can discover the state of each
CheckBox by simply using theisChecked method
which returns true or false:
Radio Buttons
The last “straightforward” input control is the
RadioButton. This works like a CheckBox in
that it very well may be in one of two states,
however the enormous contrast is that a
bunch of RadioButtons works in a gathering
and just one of them can be chosen at a time.
The justification for the expression “radio
button” is that, in the beginning of hardware,
vehicle radios had mechanical tuning buttons
organized in a line which let the driver
rapidly select a station by squeezing a button.
At the point when you squeezed another
button the current button sprung up so just
one button was squeezed out of nowhere,
ensuring that you simply paid attention to one
station at a time.
The main entanglement in utilizing
RadioButtons is ensuring you assemble them
accurately.To do this we need to utilize a
RadioGroup holder which is utilized to hold
each of the buttons that cooperate. There are
various compartments used to bunch
controls,however the most fundamental of
these is the RadioGroup.
Using Android Studio you can make a
gathering of RadioButtons by first setting a
RadioGroup holder on the plan surface and
afterward putting however many
RadioButtons inside the holder as you
require. Assuming a gathering of
RadioButtons doesn’t function as you
expect,the odds are not every one of the
buttons are inside the RadioGroup.
The least demanding method for checking,
make and alter a gathering of RadioButtons is
to utilize the Component Tree window where
you will actually want to see precisely how
they are settled.You can likewise add
RadioButtons to the holder by hauling to the
Component Tree window.
All the
RadioButtons inside a RadioGroup
consequently work so just each button can be
chosen in turn and you don’t need to
accomplish any additional work to execute
this behavior.
Summary
☐ The essential controls that make up the
majority of the
Chapter 6
Working With
Layouts
The decision of Layout is imperative to an
Android UI. The Layout is the thing that
permits you to position and by and large
organize different parts. A decent
comprehension of what is on offer in every
one of the accessible Layouts can have the
effect between a simple and a troublesome
UI, according to both the perspective of the
software engineer and the client. This is
particularly the situation to help a scope of
devices.
All of the classes and articles that make up
the Android UI are gotten from a similar base
class, the View. That is, a Button is a View as
are the Layout classes.Be that as it may,
Layouts appear to act in totally different ways
to the straightforward Button and this brings
up the issue what precisely is a Layout?
Understanding
Layouts
A Layout is a compartment for other View-
inferred objects.At the point when the Layout
is approached to deliver itself, it delivers all
of the View objects it contains and organizes
them inside the space of the showcase it
occupies.
The default Layout utilized by Android
Studio is the ConstraintLayout and we have
as of now checked out utilizing it in prior
parts, however it isn’t the main Layout you
can use with the Layout Editor.
There are six presently upheld Layouts:
☐ ConstraintLayout
☐ GridLayout
☐ FrameLayout
☐ LinearLayout
☐ RelativeLayout
☐ TableLayout
Layout Properties
Mostly you will more often than not think
about the properties that are applicable to a
control as having a place with the control, yet
a design can take care of its business in
numerous ways and requires the control to
have bunches of unmistakable properties to
decide how it is situated.As such,the
properties that a control needs to work with a
design rely upon the format picked and this
makes things hard to organize.
The least complex yet impossible method of
executing this is demand that each control
carried out each property utilized by each
format, even the ones not as of now being
utilized. This is obviously inefficient. The
answer for the issue really utilized is that
every format characterizes a settled class,
gotten from LayoutParams, that has each of
the properties it needs the control to
characterize.The control that will be put
inside the format makes an
Units
If you are going to enter a fixed size or a
location you need to know how to do it.
Android supports six units but only two, both
pixel-based units, are used routinely:
px– pixel
dp– density-independent pixel
A Control is Just a
Box
As far as a Layout is concerned, a control is
just a rectangle. Its size is given by
layout_width and layout_height and these can
be set by the control or, more often, by the
Layout. Once the Layout knows the size of
the control it can position it according to the
rules you have established using the Layout’s
properties.
If you want to know the position that a
control has been assigned then you can use its
Top and Left properties. This gives you the
position of the top left- hand corner of the
control’s rectangle. You can work out where
the other corners are by using Width and
Height properties,but to make things easier
there is also Right and Bottom
property.Notice that the position of the top
left-hand corner of the rectangle is always
relative to the Layout it is in. That is,the
position is not an absolute screen position. It
is also worth knowing that controls also
support padding, dead-space inside the
control. This is space left between the outside
edge and the content. In addition some, but
not all, layouts support margins, dead-space
outside a control that can be used to add
space between controls:
Notice that padding is a property of the
control and margin is a layout property. You
can set each margin or padding on the left,
right, top or bottom individually or specify a
single value to be used for all of them.
Gravity
Gravity is often regarded as mysterious,
partly because of its name and partly because
there are often two gravity properties in play.
Basically, gravity just sets where in a
dynamic layout something is positioned.
The FrameLayout
The FrameLayout is the simplest of all the
Layouts. It really doesn ’t do very much to
position the controls it contains and its
intended use is to host a single control, i.e. it
really does just act as a frame around a
control.
LinearLayout
The next layout we need to consider is the
LinearLayout. This is a simple layout that can
be used to do a great deal of the basic work of
organizing a UI. In fact once you start using
LinearLayout, it tends to be the one you think
of using far too often. You can use a
LinearLayout as the base Layout, replacing
the default ConstraintLayout that Android
Studio provides, or you can place a
LinearLayout within the ConstraintLayout.
In Android Studio LinearLayout occurs twice
in the Palette– once as a vertical and once as
a horizontal LinearLayout. The difference,
however, is just the setting of the orientation
property to horizontal or vertical.In other
words, you can swap a horizontal and vertical
linear layout with a simple property change.
The horizontal LinearLayout acts as a row
container and a vertical LinearLayout acts as
a column container. You can use nested
LinearLayouts to build up something that
looks like a table, but if this gets very
complicated it is better to use
ConstraintLayout. Nesting layouts like this is
also inefficient as the rendering engine has to
compute the layout multiple times to get it
right. The advice is to use a ConstraintLayout
and avoid nesting.
If you place a LinearLayout on the
ConstraintLayout then you can position it like
any other control. If you then place other
controls inside it then they will stack up
horizontally to form a row or vertically to
form a column.
This sounds easy but there are lots of ways to
use a LinearLayout.
421
Layout_weight
There ’s one last mystery of the LinearLayout
to discuss, layout_weight, a layout property
that only the LinearLayout supports. If you
assign a layout_weight to any of the controls
in a LinearLayout then the controls are
adjusted in size to fill any unused space in
proportion to their weights. The really
important part of this description is“unused
space”. What happens is that Android first
computes the layout ignoring any weight
assignments.
This means that the controls are set to the
sizes you specified. Next the system
determines what space remains unused in the
containing LinearLayout. This is then
distributed between the controls that have
nonzero values of layout_weight in
proportion to their weights. For example,
suppose we have a horizontal LinearLayout
with three Buttons all set to
wrap_content.The screen has been rotated to
provide a lot of unused space for the
example:
RelativeLayout
The RelativeLayout was the most used in the
past and it is still worth knowing about
because you will meet it in existing apps and
you might have to use it if ConstraintLayout
doesn’t work for you. It was the one that was
favored by Android Studio until the
ConstraintLayout was introduced.
Edge Alignment
The principle is that you can specify the
alignment of any pair of edges, one in the
parent and one in the child. This will move
the child control so that its edge lines up with
the parent edge, For example, top edge to top
edge. If you specify two pairs of edges then
you can change the size of the control as well
as positioning it. Forexample, top to top and
bottom to bottom makes the child control the
same height as the parent.
layout_alignParentLeft
layout_alignParentBottom
layout_alignParentRight
For example:
layout_alignRight= button1
sets the right-hand edge of the control to line
up with the right-hand edge of button1.As
continually, adjusting two edges top/base and
left/right changes the size of the control.
The attributes:
layout_above
layout_below
adjust the lower part of the control to the
highest point of the referred to control and the
base with the top respectively.
Margin Offsets
So far nothing remains at this point but to
adjust sets of edges. How would you
determine definite positions comparative with
another control or the parent?
Summary
☐ You can utilize diverse Layout holders to
make UIs. Every Layout has its own offices
for how youngster controls are situated and
sized.
Chapter 7
The
ConstraintLayout
The ConstraintLayout was new in Android
Studio 2.2 and it utilizes an extra library. The
help library is viable with all variants of
Android back to Gingerbread (2.3, API level
9) thus you can utilize the ConstraintLayout
except if you plan focusing on gadgets
running sooner than Gingerbread.
ConstraintLayout was acquainted in a work
with make design more receptive to screen
size changes, and to work on the productivity
of format by making it conceivable to try not
to settle designs. It is, basically, a further
developed RelativeLayout and on the off
chance that you have perused the part on the
RelativeLayout quite a bit of what follows
will appear to be natural. The Layout Editor
has been changed to function admirably with
the ConstraintLayout at the expense of
making different Layouts harder to work
with. This may change as Android Studio
keeps on growing yet with the accentuation
on ConstraintLayout being the answer for all
that this appears progressively unlikely.
In the past the ConstraintLayout was
immature and didn’t function admirably in all
circumstances. In Android Studio 3 the help
library has improved alongside the Layout
Editor. It currently appears to be sensible to
base all of your future applications on the
ConstraintLayout. At the hour of composing
the default variant of ConstraintLayout is
1.0.2. This backings all highlights including
chains and rules yet not hindrances and
gatherings. The current documentation
recommends that the Layout Editor upholds
obstructions and gatherings yet assuming you
utilize the default rendition of
ConstraintLayout they aren’t and they don’t
show up in the setting menu.
If you need to utilize these highlights you
need to guarantee that your venture is
utilizing 1.1.0 or later. This is at present in
beta however could well arrive at a last form
before the following variant of Android
Studio.To utilize it you want to alter the
build.gradle record to read:
conditions {
execution fileTree(dir: ‘libs’, include: [‘*.jar’]) execution
‘com.android.support:appcompat-v7:26.1.0’
execution‘com.android.support.constraint:
requirement layout:1.1.0-beta3 ’
Onlythelastlineneedschangingi.e.from1.0.2to1.1.0-
beta3.Youwillneed
toresynctheprojectandthenyouwillseegroupandbarriersinth
contextmenu.
If you have a current Layout then you can
request that Android Studio convert it to
ConstraintLayout. You should simply right
tap on the Layout in the Component Tree and
select Convert to ConstraintLayout.This can
be utilized to diminish a settled design to a
solitary“level”
ConstraintLayout,however be cautioned that
by and by it regularly gets things
exceptionally off-base. Regularly all that you
can say of a changed over format is that it
gives a beginning stage to re-implementation.
Let’s investigate how the ConstraintLayout
functions in the Layout Editor in more detail
than in past chapters.
Using the ConstraintLayout implies the main
thing that influences where a part shows are
the requirements you apply. So how would
you apply an imperative? There are two
methodologies and we have appear them both
momentarily prior parts. You can have the
Layout Editor recommend them for you
consequently, or you can apply them
manually.
Automatic
Constraints
Automatic imperatives, which we met in
Chapter 3, should make things simple. There
are two methods for getting the manager to
apply limitations dynamically:
Autoconnect mode– for a solitary component
Infer Constraints– for the whole layout
They do marginally various things and you
want to figure out how to make them work
together.
To turn Autoconnect on essentially click its
symbol at the highest point of the Layout
Editor:
To clear asingle
constraintsimply hover themouseover
thecircle that marks the location of the
constraint until it turns red and then click it:
In this manner you can specifically erase
imperatives and yet again apply the Infer
Constraints activity, or basically physically
apply a more fitting constraint.
Infer Constraints works in an extremely basic
manner. It applies limitations to parts as per
what they are nearest to.This methodology
brings about a format that works however it
probably won’t be the most sensible for
future modification.
A decent system is to turn off Autoconnect
and utilize the Infer Constraints choice each
time you place another part on the plan
surface. This permits you to develop a design
each part in turn and actually look at each
new arrangement of imperatives. You would
then be able to adjust the recently included
imperatives and move to the following
component.
Where things get troublesome is the point at
which you have a multi-part design and need
to roll out revolutionary improvements.
Regularly it is more straightforward for this
situation to erase the requirements in general
and start again.
As longas suitable constraints are in place,
the ConstraintLayout works much like the
RelativeLayout. For a component that has
been placed on its own close to the top and
left-hand edge of the screen, constraints will
be added that fix its distance from the left and
top:
Manual Constraints
You can place constraints on positioning
manually. All you have to do is drag a line
from the constraint circles on the component
to the edge you want to use as a reference
point. For example, to position the button
relative to the right side of the screen simply
drag the circle on the right of the button to the
right side of the screen and then move the
button where you want it:
Bias Constraints
So far the ConstraintLayout hasn ’t actually
given anything new, yet it has a more modern
requirement that doesn’t have a partner in the
RelativeLayout. Alluded to as“inclination”
this kind of limitation works as far as
proportions, communicated as rates and
shown as crisscross lines:
To utilize it you need to make two
requirements that “battle” one another. For
instance, assuming you drag one imperative
to the left and its partner to the right, the
outcome is a flat inclination used to situate
the control at the ideal extent of the format
size. You can accomplish an upward
predisposition by hauling requirements from
the top and the bottom.
Chains
An as of late acquainted element is the
capacity with set inclination imperatives
between parts just as to the parent
compartment. That is, you can set sets of
limitations between parts that work similarly
as a
predisposition requirement. In doing as such
you make what is currently called a“chain” of
parts. The justification behind acquainting
chains is with make it simpler for
ConstraintLayout to make the kind of thing
that you would have used
A Chained Keypad
To show how helpful chains are, we should
carry out a keypad of the sort that we utilized
in the number cruncher project toward the
finish of Chapter 3.
First spot nine buttons on the plan surface in
an unpleasant 3 by 3 grid:
Selecteachrowin
turnandusetheChain,CreateHorizontalChaincommand
toconverteachoneintoachainofthreebuttons:
Then select the three chains, i.e. all nine
buttons, and use the Chain, Create
VerticalChaincommandtocreatethegrid:
Guidelines
The last situating apparatus you have
available to you is the rule. You would now
be able to relocate a level or vertical rule on
the plan surface and use it to situate different
parts. The main thing about rules is that they
don’t exist as a View item, or whatever else
in the last format. A rule is an item in the
Layout Editor and any limitations that you set
utilizing it are changed over to situating that
makes no reference to the rule when the
application is run.
To add a rule you should simply utilize the
Guidelines tool:
Once the rule has been added, you can drag it
to the ideal area and afterward position parts
comparative with maybe it was a part by its
own doing. You can set any limitation that
you can use with a part, including
predisposition. Notice that assuming you
move a rule any parts of the UI that are
compelled to is will likewise move– this can
be very useful.
Groups
Notice that this is just accessible in
ConstraintLayout 1.1.0 or later – see the
beginning of the section for more
information.
A Group enables you to make gatherings of
parts. Right now this just gives a
straightforward method for changing the
perceivability of a bunch of parts. You can
put a gathering on the plan surface utilizing
the Add Group menu command.
The Group is least demanding to use in the
Component Tree.You can drag quite a few
parts and drop them on the Group. Notice that
there is no sense wherein the parts are
offspring of the Group, it’s anything but a
compartment. The Group essentially keeps a
rundown of the parts that it controls the
perceivability of:
Sizing
In contrast with situating, estimating a part is
practically minor yet with some intriguing
twists.
You can see how the component is sized in
the Attributes window. The type of lines
shown inside the component indicate the size
of the component and its relation to its
content. Straight lines indicate a fixed size:
Next
place two Buttons on the plan surface and,
utilizing the Component Tree simplified them
onto the barrier:
Constraint Attributes
As you would figure, there are ascribes
basically the same as those utilized by the
RelativeLayout which set the limitations for a
ConstraintLayout. To see each of the
properties you need to tap on the View all
ascribes symbol at the upper right of the
Attributes window– the twofold arrow.
For instance, assuming that you examine the
Attributes window you will see:
Constraints
Left_toLeftOf
This prompts you to supply the id of the other
control being utilized in the
Troubleshooting
The ConstraintLayout gives a method of
making responsive designs that change in
accordance with the size of the screen.
Notwithstanding, doing this viably is
troublesome. The measure of knowledge
required works out in a good way past what
the Infer Constraints device has. It might
even be past a human. A less difficult,
however more work-concentrated way, is to
give a different design to profoundly unique
screen sizes and use requirements to make
little adjustments.
Chapter 8
Programming The
UI
If you want to be a really good Android
programmer,not only do you need to know
how to create a UI, but also how the UI is
created. To be really confident in what you
are doing, you need to understand some of
the inner workings of the Android graphics
system. This is also essential if you want to
modify the UI in code and work with menus.
A UI Library
There are lots of different UI construction
kits for Java and other languages, AWT,
Swing, Qt, MFC, WPF and on, and you might
think that mastering them all would be a
difficult, if not impossible, task. In fact it is a
lot easier than you might think because most
UI libraries use the same general approach
and the Android UI library, which doesn’t
seem to have a given name, is no different.
Let’s take a careful look at how it works.
An Activity has a window associated with it
and this is usually the entire graphics screen
of the device it is running on. In other words,
an Activity can allow other objects to draw
on the device’s screen. However, rather than
simply providing direct access to the graphics
hardware, there is an extensive set of classes
that make building a UI and performing
graphics operations easier.
Before we look at general graphics we need
to first find out how the UI is constructed.
The View
The basis of all UI components and general
2D graphics is the View class. This is a
general-purpose class that has lots and lots of
methods and properties that determine how it
will display the component or other graphics
entity it represents. It also takes part in the
event handling system, which means Views
can respond to events. There are View classes
that implement all of the standard
components that you make use of in the
Android Studio Layout
Editor,i.e.Button,TextView and so on.
Using
setContentView
How do you set a View object to show in the
Activities window? The answer is that you
use the Activities setContentView method,
which is what we have been doing all along.
To see this in action, start a new Basic
Activity project
and change onCreate to read:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) val b = Button(this)
setContentView(b)
}
Don’t forget to use Alt+Enter to add the
import statements needed to allow you to use
the Button class, and don’t leave any code in
onCreate that would use other View objects
such as the menu.
The ViewGroup
If an Activity can only show a single View
object, how can we ever create a complex UI
with multiple buttons, textViews and other
components? The answer, and you probably
already guessed it, is that there are Layout, or
ViewGroup, objects which can be used to
host other View objects. You already know
about using Layouts in the Layout Editor or
in an XML file, but they, like all UI elements,
correspond to particular classes that do the
actual work.
A ViewGroup can display multiple View
objects. So in nearly all cases the View object
that is associated with an Activity is a Layout
View. When the Activity asks the Layout
View to render itself, by calling its onDraw
method, the Layout calls the onDraw method
of each of the View objects it contains and
puts them together to make a single result. Of
course,it also performs a layout operation
positioning and sizing the View objects it
contains.
val b = Button(this)
b.text=“Hello Button”
linLayout.addView(b)
setContentView(linLayout)
}
If you run this program you will see a button
at the very top left of the screen.
460
Programming
Layout Properties
At the moment we are relying on default
settings for the properties,and the layout
properties in particular,of the View objects
we are creating. However, in practice you
could spend the time and lines of code to set
all of the properties needed to create any user
interface and layout you wanted to.
You now know how to create a UI
completely in code. All you have to do is
create all of the objects you need, set their
properties and add them to suitable layout
objects. This is a little more complicated than
you might think because each layout type has
a different set of layout properties. Exactly
how this is done is easy enough, but if you
don’t want to know about it at this stage you
can skip ahead as it doesn’t change any of the
general principles.
As explained in the previous chapter, each
type of Layout has an associated class
derived from LayoutParams called
layout.LayoutParams where layout is the
name of the Layout class. For example,
LinearLayout has the
LinearLayout.LayoutParams class, which is
used to define all of the layout properties that
a View object can use when added to a
LinearLayout object.
XML Layout
So far the principles of the graphic system are
simple enough. Every control or component
corresponds to a View object and you can
build a UI by creating View objects in code
and adding them to Layouts. You control the
way the View objects are arranged using the
LayoutParams object or by directly setting
properties. An Activity will draw its View
hierarchy to the screen when it needs to.OK,
this is how to create a UI in code,but so far
we have been building a UI using the Layout
Editor. How does this relate to the View
hierarchy?
The Layout Editor creates an XML file which
describes the View hierarchy that you want to
create. The way that this works is fairly
obvious. Each tag in the XML file
corresponds to a View object for which you
want to create an instance.For example:
<LinearLayout>
</LinearLayout>
creates an instance of a LinearLayout object.
Nesting tags within a layout indicates that the
objects created need to be added to the layout
as child Views. For example:
<LinearLayout>
<Button />
</LinearLayout>
android:text=“New Button”
/>
android:layout_width= “wrap_conte
nt”
android:layout_height=“wrap_conte
nt”
/>
That is really all there is to it. The XML
defines a hierarchy of objects and their
properties and the system reads the file and
creates the objects.This use of XML as an
object instantiation system is not an
uncommon one. Of course, the XML created
by the Layout Editor looks a lot more
complicated than the examples above, but
this is mainly because of the number of
attributes it defines. The basic idea is still the
same.
Inflation Theory
The final big question to be answered is how
does the XML get converted into a real object
hierarchy? The answer to this is to use
an“inflater”. To inflate a layout is Android
jargon for instantiating the objects defined by
an XML file. You normally don’t have to call
an inflater because the system does it for you
behind the scenes, but you can if you want to.
For example, to inflate a layout you would
use an instance of the LayoutInflater.
Normally you wouldn’t create a fresh
instance. Instead you can simply use an
existing one supplied by the system using the
LayoutInflater property of the Activity. Once
you have the LayoutInflater you can use one
of its many inflate methods to create a View
object hierarchy as specified by the XML.
Which method you use depends on where the
XML is stored. You can simply supply a
resource id for an XML file included in the
res directory. For example, to inflate the
usual activity_main.xml layout you can use:
val inf = layoutInflater
val myView = inf.inflate(R.layout.activity_main,null)
setContentView(myView)
The second parameter of inflate can be used
to provide a View object to act as the root
container for the inflated View hierarchy. The
container is just used as a reference“parent”
for the purposes of calculating the layout.
That is, it simply provides the container that
everything has to fit into according to the
layout rules. Of course this is entirely
equivalent to the usual:
setContentView(R.layout.activity_main)
Summary
☐ All of the UI components are derived from
the View class.
☐ An Activity can host and display a single
instance of the View class set by one of its
setContentView methods.
☐ You can create instances of View objects
in code and set them to be displayed by the
Activity.
Chapter 9
Menus – Toolbar
A UI isn ’t just made up of buttons and other
widgets or components; the menu is still a
useful way of letting the user select what
happens next. Android’s menu system is easy
to master.We also need to find out about the
Toolbar implementation of the action bar.
There is a menu Layout Editor in Android
Studio 3.0 and it works quite well, but it is
still worth knowing how to create the XML
yourself. The basic principles of menu
creation are the same as for building a UI in
that a menu is a collection of View objects.
You can create the View objects in code or
you can use an XML file and a special
inflater, a MenuInflater, to convert it into the
objects. Defining a menu is more or less the
same process every time, although the way in
which you use the menu varies according to
where and when the menu is shown, but even
this follows roughly the same steps. Let’s
look a the general idea first.
Creating a Menu
Resource
Menus are generally defined by a menu
resource file, which is an XML file whichis
rendered to createthemenu.All menu
resources arestoredin the app\res\menu
directory. Ifyou right click on this directory
you can select the New, Menu resource
option and type in a name–all lowercase as
usual:
"http://schemas.android.com/apk/res/android">
<item
android:id=“@+id/file” android:title=“File”> ” android:title=“Open”
/>
<item
android:id=“@+id/create_ne w” android:title=“New” />
<item
android:id=“@+id/open
</menu>
</item>
</menu>
Displaying a Menu
There are four different ways you can display
a menu:
1. Action bar such as the App Bar
2. Context menu
3. Contextual action Bar (CAB)
4. Popup
The action bar or App bar was introduced in
Android 3 as a replacement for the original
options menu and has become the standard
primary menu for apps. With Android 5 a
new way of implementing it was introduced,
namely the Toolbar, which is a standard
widget that can be edited using the Layout
Editor. This makes it easier to integrate and
work with. If you want to use the ActionBar
in earlier versions of Android you need to
make use of the Support Library – this is
automatically included when Android Studio
creates a project for you.
The context menu is a popup menu that
appears in response to a long click on a
component of the UI.
The Contextual Action Bar appears at the top
of the screen when the user long-clicks on a
UI element and it is supposed to be used to
provide actions that are appropriate for the
item that has been selected. It too needs the
Support Library to work with older versions
of Android.
The popup menu can be displayed in
response to almost any user action you care to
use. It appears next to the View object that
causes it to be displayed. For example you
could have a button that displays a popup
when clicked or a popup could appear when a
user types something into a text field. It is
difficult to know exactly when to use a popup
menu. Logically the next step would be to use
the XML file we just created to display either
a CAB or a popup, but it is better to start with
the default project type as it generates the
code and menu resource file needed to
implement an action bar, the Toolbar, and it
is used in most applications. The remaining
menu types are the topic of the next chapter.
android:layout_height= “wrap_content”
android:theme=“@style/AppTheme.AppBarOverlay”>
app:popupTheme=“@style/AppTheme.PopupOverlay”
style=“@style/AppTheme” />
<android.support.v7.widget.Toolbar
android:id=“@+id/toolbar”
android:layout_width=“match _parent”
android:layout_height=“?attr/a ctionBarSize”
android:background=“?attr/colorPrimary”
</android.support.design.widget.AppBarLayout>
<include layout=“@layout/content_main” />
...
<item
android:id=“@+id/action_settings”
android:orderInCategory=“100”
android:title=“Settings”
app:showAsAction=“never” />
</menu>
You can see that this defines a single menu
with a single item with the title “Settings”.
There are some new attributes being used in
the item tag.The showAsAction attribute is
important for the way the Toolbar,or action
bar,
}
The onCreateOptionsMenu is called once
when the Activity starts.Before Android 3 it
was called each time the menu was displayed
on the screen, but now the App bar is always
on display. How to change a toolbar is
discussed later.
Where's My
Toolbar?
If you try any of this out then there is a
chance that you will do everything correctly
and yet your Toolbar will not show.
There are only two common reasons for this:
Responding to Menu
Events
You can attach click event handlers to the
various items in a menu in the usual way.
This is something that is often overlooked
because there is a simpler and standard way
of doing the job. However, it is worth seeing
the direct method if only to convince yourself
that a menu is just another part of the View
hierarchy that your application displays. If
you aren’t fully familiar with how to attach a
click event handler to a View object, refer
back to Chapters 4 and 5.
When you inflate a menu resource in
onCreateOptionsMenu what happens is that
the View hierarchy that is created when you
inflate the XML is added to the current menu.
This is passed into the onCreateOptionsMenu
event handler in the menu parameter:
override fun onCreateOptionsMenu(menu: Menu): Boolean {
Next you use the inflater and inflate the
resource:
menuInflater.inflate(R.menu.menu_main, menu)
After this, menu contains the View hierarchy,
that is the entire menu as created so far.
At this point you might be thinking that you
can access the menu items using
process event
fals
e
}
}
You can also add an event handler for the
menu in the XML resource using the
android:onClick attribute. The event handler
has to have the same signature as the one
demonstrated above,i.e.it has to return a
boolean and have a single MenuItem
parameter.
For example:
fun myOnClick(
item:MenuItem):
Boolean { return true
}
and:
<item android:id= “@+id/action_send” android:title=“Send”
app:showAsAction=“ifRoom”
android:icon=“@android:drawable/ic_menu_send”
android:onClick=“myOnClick”
/>
You can use this method to connect as many
individual event handlers as you
(item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
(item.itemId) {
R.id.action_settings ->
true R.id.action_send -> {
}
}
super.onPrepareOptionsMenu(menu)
}
}
Now assuming you run the program you will
find that each opportunity you select the
Settings menu two or three New Items are
added to the menu:
(checkBox.isChecked()) {
menu?.add(Menu.NONE, 10, Menu.NONE,“New Item”)
} else {
menu?.removeItem(10)
}
return super.onPrepareOptionsMenu(menu)
}
(checkBox.isChecked()) {
if (menu?.findItem(10) == invalid) { menu?.add(Menu.NONE, 10,
Menu.NONE,“New Item”)
}
} else {
menu?.removeItem(10)
}
return super.onPrepareOptionsMenu(menu)
}
Finally, how would you set different
properties of the MenuItem you have added?
The appropriate response is that add returns
the MenuItem made. So to set the new thing
to show in the activity bar you would utilize
something like:
val menuItem= menu?.add(Menu.NONE, 10, Menu.NONE, “New Item”)
menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_AL WAYS)
Controlling the
Toolbar
There are two or three inquiries that actually
remain. You can perceive how to add things,
submenus and for the most part control what
the Toolbar shows, Nonetheless shouldn’t
something be said about controlling when it
is shown or what it looks like? The response
to these inquiry depends on working with the
ActionBar object and as you would expect
this isn’t an overall thing to all menus.
ActionBar has heaps of highlights for
showing menus in various ways and to cover
it totally would take an excessive amount of
room.However,it merits knowing a portion of
the fundamental customizations that you can
apply. You can get the ActionBar object in an
Activity utilizing supportActionBar or
actionBar properties. When you have the
ActionBar object you can utilize its show()
and stow away() techniques to show/conceal
it as required: supportActionBar?.hide()
Similarly you can change the title and caption
showed in the activity bar: supportActionBar?.title =“My
Action Bar”
supportActionBar?.subtitle =“My Subtitle”
There are
numerous different properties and strategies
that you can use to alter the manner in which
the activity bar looks and behaves.
Summary
☐ A menu is an order of View protests very
much like any UI element. ☐ You can make
a menu in code, however utilizing a menu
XML asset document is the most widely
recognized method of doing the job. ☐ There
are Menu articles and labels which go about
as compartments for Item protests and tags.
☐ Submenus can be made by settling Menu
objects inside other Menu objects.
☐ Menu things can have a title, symbol, and
numerous different qualities which oversee
how they are displayed.
☐ There are four distinct ways you can show
a menu: App bar/Toolbar; setting menu;
logical activity mode; popup.
Chapter 10
Menus – Context and
Popup
As well as the generally useful Toolbar which
fills in as an application ’s principle menu,
there are three other regularly experienced
menus– the setting menu, the context oriented
activity menu, and the popup menu. They
share the essential Android way to deal with
menus while having some unmistakable
characteristics.
The setting menu is a drifting menu that
presentations orders that take the thing
clicked as their subject. For instance,
choosing a line in a table may raise a setting
menu that permits you to erase or move the
thing. The setting menu is straightforward
and genuinely simple to carry out, yet there is
a slight turmoil brought about by the
presentation of the Contextual Action mode,
a setting menu as an activity bar which is
upheld in Android 3 or more. A popup menu
shows a rundown of things and is moored to
the View that summoned it. It tends to be
utilized, for instance, to give extra decisions
to tweak an action.
<item
<item
android:title=“MyItem1”
android:id=“@+id/myitem1”/>
android:title= “MyItem2”
android:id=“@+id/myitem2”/>
</menu>
registerForContextMenu(button)
registerForContextMenu(checkBox)
}
You can see what’s going on here, We
observe the Button and CheckBox items and
register them utilizing
registerForContextMenu.Later this a long
snap on either UI part will trigger the
onCreateContextMenu event.
}
If you currently run the program you will see
that a similar setting menu seems when you
long snap on either the Button or the
CheckBox:
(item.itemId) {
R.id.myitem1 → {
myitem1 action
true
R.id.myitem2 → {
myitem2 action
true
}
else - >
super.onContextItemSelected(item)
}
}
(item.itemId) {
R.id.myitem1 - > {
textView.text =
“item1” true
R.id.myitem2 - > {
textView.text =
“item2” true
}
else - >
super.onContextItemSelected(item) }
}
Contextual Action
Bar
The setting menu is not difficult to utilize Be
that as it may later Android 3 the Contextual
Action Bar menu is liked as it expands the
conduct of the move bar,assuming control
over the App bar position at the highest point
of the screen. However, it works, and is
executed, freely of the App bar.
}
The Callback object has four techniques
every one of which is called as a component
of the menu’s life cycle. You really must
supplant the TODOs with code that profits
the right sort for each method.
You need to ensure that when you import the
class you import the rendition from the help
library:
import android.support.v7.view.ActionMode
As you would well theory, to cause the menu
to seem you need to fill in the subtleties for
the onCreateActionMode method:
abrogate fun onCreateActionMode(
mode: ActionMode?, menu: Menu?): Boolean {
mode?.menuInflater?.inflate(R.menu.mycontext, menu) return true
}
}
Now when you long click the button a new
context action bar menu appears above the
usual App bar:
mode: ActionMode?,
thing:
MenuItem?):
Boolean {
return false
}
supersede fun onCreateActionMode( mode:
ActionMode?,
menu: Menu?): Boolean { mode?.menuInflater?.inflate(R.menu.mycontext,
menu) return true
}
}
ThePopupMenuconstructoraccepts the
context andtheViewobjectit will be displayed
next to. Usually this is the View object that
the user clicked or interacted with i.e. the
button in this case. Next we inflate the menu
as usual by using the Popups own inflater
which adds the menu to the Popup. Finally
we call Show which displays thePopup:
The menu is quickly excused assuming the
client taps on a thing or on some other piece
of the display.
Obviously on the off chance that you were
truly utilizing the popup menu you would
likewise deal with the thing click event:
popup.setOnMenuItemClickListener { thing >
textView.text =
item.title false
}
As before you would utilize a when to find
which thing the client had chosen and follow
up on that selection.
The total code is:
abrogate fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
Summary
☐ The setting menu is summoned for all
View objects in the UI that are enlisted
utilizing registerForContextMenu(View).
Chapter11
Resources
So far we have disregarded assets, yet the
subject can be overlooked no more. Assets
fill too significant a need in Android. They
not just make limitation more
straightforward, they are critical to making
applications that adjust to the gadget they are
being run on.
Why Use Resources?
Any limited scale information that your
application utilizes – strings, constants,
designs, format documents– should be
generally included as assets rather than hard
coded into your application. For instance, up
to this point we have entered any text that the
UI required straightforwardly as a string
property estimation. For a button this
approach has meant setting the Textproperty
bytypinginastringsuchas "HelloWorld".
Android Studio does it best to save you this
effort. If you run the Warnings and Errors
"linter" by clicking on the red icon in the
Layout Editor, then for any string you have
entered as a literal into the Attributes window
you will see awarning:
</resources>
☐ drawable/
Any realistic– normally .png, .gif or .jpg yet
there are a scope of other less often utilized
sorts. The standard is– assuming it’s in any
sense a realistic it has a place in drawable.
☐ design/
We have been utilizing formats since we
began programming Android and XML
format is an asset assembled into your
application prepared to be used.
☐ menu/
The XML records that determine a menu are
additionally assets and aggregated into your
app.
☐ values/
XML files that define simple values such as
strings, integers and so on. You can imagine
these as characterizing constants for your
Typically:
• arrays.xml for composed arrays
• color.xml for shading values
• dimens.xml for dimensions
• strings.xml for strings
• styles.xml for styles.
Drawables
Drawables are somewhat unique in relation to
different assets in that there is no XML
record that characterizes them. To make and
utilize a drawable you should simply
duplicate the realistic record that you need to
use into the drawable/index. You needn’t
bother with XML to characterize the asset in
light of the fact that the asset’s id is only the
document name.
The most ideal way to clarify how drawable
assets work is through a straightforward
model. To make a jpg bitmap asset you
should simply duplicate the jpg record into
the right asset index. Android Studio
naturally makes the drawable/catalog for
yourself and you should simply duplicate the
bitmap document into it– however how?
The primary comment is that the record name
for a drawable asset can just hold back lower
case letters and digits. Assuming the first
document name doesn’t adjust to this
example you can rename it later you have
replicated it into the directory.
There are two genuinely simple ways:
Values
The simplest of the asset envelopes to utilize
is likely qualities/,yet it additionally will in
general be the least frequently utilized. The
strings.xml record will in general be utilized,
yet the others are underutilized.The
justification behind is that the framework will
in general incite you to enter strings as assets
and there is an undeniable benefit to string
assets in that they permit simple confinement.
Nonetheless,placing constants of different
kinds in assets is a decent idea.
Although the documentation just notices
string, clusters, shadings, aspects and styles,
you can incorporate a more extensive scope
of information types in the XML file:
☐ Bool
<bool name=“resourcename”>true</bool>
☐ Integer
<integer name=“resourcename”>1234</integer>
☐ String
<string name=“resourcename”>A String</string>
</number array>
☐ Typed Array
<array name= “resourcename”>
<item>resource</item>
<item>resource</item>
</array>
Dimension is likewise two straightforward
worth resources:
☐ Dimension is basically a number worth
complete with a units
IDs
Ids are esteem assets and can be set up very
much like some other worth asset. For
instance, to set up an id for a button you may
use:
<item type=“id” name=“resourcename”/>
Notice that this is somewhat not the same as
other worth assets in that you don’t need to
offer a benefit. The explanation is that the
framework
Accessing Resources
in Code– The R
Object
For a significant part of the time you truly
don ’t have to waste time with getting to
assets in code on the grounds that the task is
finished for you consequently. For instance,
in the event that you relegate a string asset to
a button’s text:
<Button
android:text=“@string/Greetin
g”
Conditional
Resources
So far assets have recently been a method for
getting information into your application.
You may have imagined that assuming there
was one more method for doing the work
then it very well may be comparable.
Notwithstanding,Android Resources are vital
to altering your application so it works with
the wide scope of gadget types and client that
an Android application needs to adapt to. The
cunning part is that you can utilize contingent
assets to give a bunch of assets modified for
the current gadget at runtime.
The thought is basic. First you give a default
asset record. This is the one that is situated in
the proper index,/res/values say, however
presently you use qualifiers as a component
of the catalog name.
For instance, you can make a registry
called/res/values-es which is planned to give
asset esteems to the application when running
on a gadget set to a Spanish language region.
What happens is that first any qualities that
you have characterized are taken from the
XML records in the qualities registry, these
are viewed as the default. Then, if the
application is running on a Spanish language
gadget the XML records in qualities es are
handled and any assets with a similar name
supplant the ones gave by the defaults.
You can see that this gives a genuinely
simple method for ensuring that your
application presents a UI in the nearby
language, however there are a greater number
of qualifiers than just area, and these permit
you to alter the application for different
elements of the gadget. You can even pile up
qualifiers as a feature of envelope names to
get more exact focusing on. For instance, the
index esteems es-little would possibly be
utilized assuming that the language was
Spanish and the screen was like a low
thickness QVGA screen. The main thing to
be cautious about is that the qualifiers are
utilized in the request where they are
recorded in the documentation. There are
qualifiers for district, screen thickness, size
and direction, gadget type, night v day,
contact screen type, console accessibility and
stage adaptation (API level). You can think
that they are totally recorded in the
documentation, yet much of the time this is
pointless in light of the fact that Android
Studio assists you with making qualified
resources.
If you select an asset catalog, values say, and
right snap you will see a New,Values asset
document in the setting menu. On the off
chance that you select this choice then the
New Resource File discourse opens.You can
utilize this to make an asset file
– enter its name - and you can apply any
qualifiers you need to by essentially choosing
from the rundown of accessible quantifiers to
the left:
and:
values-es/strings.xml
This isn’t what the undertaking program
shows naturally which is the Android view. It
shows the new document as being in the
qualities index inside another envelope called
strings.xml.
504
Android Studio
Translation Tools
Android Studio likewise has some extra
instruments to permit you to see restrictive
assets. The World symbol showed in the
Layout Editor permits you to choose an area.
It merits utilizing this to check that your
application great examines other locales:
505
Chapter
12 Bitmap
Graphics
Android illustrations is a gigantic subject, yet
you need to begin some place. In this section
we look a straightforward 2D bitmap designs,
which is regularly all you really want, and
find the essential standards of Android
graphics.
Android Graphics
Graphics support in Android is broad – from
the basic showcase of pictures and 2D
illustrations through liveliness and on to full
3D delivering. To cover everything needs a
different book, and surprisingly then there
would be themes left immaculate. This part is
a prologue to the base you really want to be
aware of 2D bitmap designs in Android. It
isn’t all you really want to know to take care
of business, however it is sufficient to kick
you off on numerous normal straightforward
illustrations undertakings. With this
establishing you’ll likewise be in a situation
to search out a portion of the extra data you
want to do the more uncommon things.
The critical distinction between this record of
Android illustrations and the normal
methodology you find in different reports is
that it focuses on the standards just as the
how-to. Before the finish of this section you
ought to have a reasonable thought of what
the distinctive Android illustrations classes
are everything about.
The Bitmap
You could say that the bitmap is the
establishment of any utilization of Android
designs. The explanation is that regardless of
how a realistic is determined or made, it is a
bitmap that is in the end made and shown on
the screen.
The ImageView
Control
How would you be able to see a Bitmap that
you have recently made? The basic answer is
to utilize an ImageView control.Thisisn’ta
popular approach,however,because it isn’t as
flexible as alternatives such as overriding the
onDraw event handler. All things considered,
the ImageView control is extremely simple to
utilize and adequate for some tasks.
Start another venture and spot an ImageView
into the UI, tolerating the defaults. The
Layout Editor wont let you place a void
ImageView on the plan surface so select any
drawable as an impermanent filler. As an
exhibition of how you can utilize the
ImageView to show a Bitmap, change the
onCreate occasion controller to read:
supersede fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
}
If you run the program you will see a
genuinely enormous red square seem where
the ImageView control has been placed:
Canvas
You can simply utilize a Bitmap and work
with individual pixels, however this is
definitely not an extremely“undeniable level”
method for making designs.What we really
want are some bigger scope strategies that
draw helpful things like lines, square shapes,
circles thus on.
The Bitmap object doesn’t have this kind of
strategy, however the Canvas object does and
you can utilize it to draw on any Bitmap. That
is you make a Canvas object, partner it with a
Bitmap, and you can utilize the Canvas item’s
techniques to draw on the Bitmap. There are
bunches of various Canvas drawing
strategies, and surprisingly an office to
change the essential direction framework to
anything you want to utilize, yet we need to
begin some place so a basic model first.
A First Graphic
Now we have a Paint object we can draw a
line:
c.drawLine(0f, 0f, 500f, 500f, paint)
This draws a line from 0,0 to 500,500 and as
the Bitmap is 500 by 500 pixels
paint.color=Color.GREEN
c.drawRect(20f, 300f, 180f, 400f, paint)
paint.color=Color.BLACK
paint.textSize=50f
c.d rawText(“Hello Graphics”,0,14,90f,80f,paint)
imageView.setImageBitmap(b)
Transformations
Now we come to one of the more modern
choices that Canvas offers. Prior to anything
is drawn, the directions you supply are
followed up on by a change framework.
Naturally this is set to the personality grid
which leaves the directions as they were.
Nonetheless, the accompanying strategies
change the change matrix:
☐ rotate(float degrees)
turn about the beginning through degrees
☐ rotate(float degrees, float px, float py)
pivot about the point px,py through degrees
☐ scale(float sx, float sy)
scale about the beginning by sx and sy
☐ scale(float sx, float sy, float px, float
py) scale about the point px,py by sx
and sy
☐ skew(float sx, float
sy) slant by sx and sy
☐ translate(float dx, float
dy) interpret by dx and
dy
There are likewise a few properties and
techniques that let you work
straightforwardly with the change matrix:
☐ matrix
set or get the change matrix
☐ concat(Matrix matrix)
increase the change grid by the lattice
provided
If you definitely know how networks and
change frameworks work then this will be
appear to be very direct. If not, there are a
great deal of traps holding on to entangle you.
The fundamental one, that inconveniences
pretty much everybody right away, is that the
request where you do things matters. An
interpretation followed by a turn isn’t exactly
the same thing as a pivot followed by an
interpretation. Attempt it on the off chance
that you don’t trust me. Another is that these
changes change the direction framework and
influence nothing you have effectively drawn.
They possibly change what happens when
you draw something later the change has
been applied.
For instance, we can pivot the text in the past
example:
paint.color=Color.GREEN
c.drawRect(20f, 300f, 180f, 400f, paint) c.rotate(15f)
paint.color=Color.BLACK
paint.textSize=50f
c.drawText(“Hello Graphics”,0,14,90f,80f,paint)
In this case there is a 15 degree rotation after
the rectangle has been drawn
and before the text is drawn. The result is that
the rectangle stays where it
was but the text is rotated:
c.restore()
c.rotate(15f)
paint.color=Color.BLAC
K paint.textSize=50f
c.drawText(“Hello Graphics”,0,14,90f,80f,paint)
A Logical Approach
to Transforms
One way to deal with monitoring changes is
to draw everything focused on the beginning,
and afterward decipher, scale and turn it to its
last position. For instance, to draw the
rectangle:
c.drawRect(20f, 300f, 180f, 400f, paint)
pivoted through 45 degrees you would
initially draw a unit square fixated on the
origin:
c.drawRect(- 0.5f, - 0.5f, 0.5f, 0.5f, paint)
then you would then scale it to its ideal size:
c.scale(160f,100f)
and turn it:
c.rotate(45f)
Finally you would move it to its right
location:
c.t ranslate(100f, 350f)
If you evaluate these means, you will find
that you don’t get what you anticipate.The
explanation is that we have been changing the
article: draw a square, scale the square, pivot
it and move it to the ideal location. However,
the Canvas changes don’t change graphical
items yet the
val xmax=10f
val xmin=0f val
ymax=10f val
ymin=0f val
width=500f
val height=500f
c.drawLine(0F, 0F, 10F, 0F, paint) c.drawLine(0F, 0F, 0F, 10F, paint)
c.drawLine(0F, 0F, 10F, 10F, paint)
c.restore()
This draws tomahawks and a 45 degree line:
Simple Animation
To wrap this section up we will invigorate a
ball ricocheting around a Canvas, or a Bitmap
depending your perspective. This may appear
to be an odd subject to end on, particularly
since we won’t do the occupation in the
manner that most Android developers would
go with regards to it. Indeed Androidhasa
range of different animation facilities– View
animation, Value animation and so on.
Nonetheless, not a solitary one of them shows
the essential way that unique designs work
and before you continue on to learn more
complex methods of making activity it is a
smart thought to discover how things work at
the most minimal level.
This model shows you something liveliness,
yet additionally about the issues of making
dynamic illustrations of any sort in the
Android UI. One admonition– don’t accept
this is everything to be aware of Android
movement or that this is the most ideal way
to do things.
To quicken something in the easiest and most
direct manner you should simply draw the
shape, change the shape, eradicate the old
realistic, and draw it again.
In many frameworks this is generally
accomplished at the least conceivable level
by utilizing a clock to call an update work
which deletes the shape, does the update to
the shape and afterward draws it at its new
area. You can adopt this strategy in Android,
yet for different reasons it isn’t the status quo
normally done. It must be conceded that there
are some slight challenges, yet beating them
isn’t hard and is very instructive.
To perceive how everything functions we
should simply skip a “ball” around the screen.
This is pretty much the“hi world” of basic 2D
sprite-based graphics.
So start another Android Studio venture and
spot an ImageView on the plan surface. This
is the main UI component we need.
We want a bunch of items and qualities that
are available from various strategies and that
have a lifetime as old as application. The
easiest method of accomplishing this is to set
up private properties:
private val b = Bitmap.createBitmap(width, height,
paint.setAntiAlias(false)
paint.Style = Paint.Style.FILL
}
First it sets the shading to white and draws
the ball, a circle. This deletes the ball at its
old position, recollect the foundation is white.
Next it refreshes the situation by adding the
speeds toward every path. To ensure that the
ball skips we test to check whether it has
arrived at a limit and assuming it has its
speed is switched. At last, the shading is set
to red and the ball is drawn at the new
position.
If the function was to stop at this point then
everything compiles and runs, but you won't
see the ball move. The reason is simply that
the UI is drawn once at when the program is
initially run and then only when it is
necessary becausethe user hasinteracted
withitortheorientationhas changed,etc.As a
result the bitmap displayed by the ImageView
object would be changed every 10
milliseconds, but it would not be redisplayed.
To make the UI update we want to call the
ImageView’s negate strategy which
essentially tells the UI to redraw it.
Notwithstanding, assuming you put this in
toward the finish of the update work you get
a blunder message something like:
android.view.ViewRootImpl$CalledFromWrongThreadEx
Only the first string that made a view chain of
importance can contact its views.
, 0, 10)
This resembles a wreck of settling and wavy
supports, yet you ought to have the option to
follow the logic.
Now when you run the program you will see
the red ball bob gradually and easily around
the screen.How great the movement is
depends what you
import
android.support.design.widget.Snackbar import
android.support.v7.app.AppCompatActivity import
android.view.Menu
import android.view.MenuItem
import
kotlinx.android.synthetic.main.activity_main.* import
android.graphics.Bitmap
import
android.graphics.Canvas
import android.graphics.Color import
android.graphics.Paint
import
kotlinx.android.synthetic.main.content_main.* import java.util.*
private var x = 463f private var y = 743f private var vx = 1f private var vy =
1f private var r = 30f
c.drawColor(Color.WHITE)
paint.setAntiAlias(false)
paint.Style = Paint.Style.FILL imageView.setImageBitmap(b)
val clock = Timer()
timer.schedule(object : TimerTask() {
} imageView.invalidate(
)
fun update() {
paint.color = Color.WHITE c.drawCircle(x, y, r, paint) x = x + vx
y = y + vy
if (x + r >= width) vx = vx if (x - r <= 0) vx = - vx if (y + r >= stature) vy =
vy if (y - r <= 0) vy = - vy paint.color = Color.RED c.drawCircle(x, y, r,
paint)
}
There is such a long way to go regarding
designs it is hard to choose things you want
to know. To discover more with regards to
how the standard UI functions you want to
investigate the OnDraw occasion and how to
make your own View object that render
designs. You really want to look into
Android’s vector illustrations utilizing shapes
and way. You really want to be familiar with
the various kinds of liveliness that are
accessible and in the end you really want to
learn
about OpenGL and its help for equipment
sped up 2D and 3D graphics.
Summary
☐ The subject of Android designs is colossal
and there is in every case more than one
method for moving toward any errand. This
section is a first gander at what you may call
UI-based graphics.
Chapter 13
LifeCycleOfAnActivity
One of the things that you need to become
acclimated to when programming for a
versatile stage is that your application can be
closed down and restarted absent much by
way of caution. This is the kind of thing that
frequently makes amateurs and developers
from different stages commit errors.You need
to figure out how to adapt to this beginning
stop presence and that, for an Android
application, it is an intense life simply
attempting to remain alive.
I as of late experienced an Android
application, made by a huge notable
organization, that requested that I fill in a
structure. I was going to press the Submit
button when I unintentionally shifted the
telephone and the screen auto-rotated.
When I looked again there was a clear
structure! I needed to begin once again and,
being a
developer,Icouldn'tresisttestingtoseeifthedata
vanishedfromtheform when I rotated the
phone a second time–it did! The
programmers fromthis high-profile company
had no idea about creating an Android app
beyond the basics.
Don’t fall into a similar snare. Look into
application lifetime, state and continuing
information. It might seem like an exhausting
subject yet it is imperative to the working of a
UI.
Lifetime and State
Mostprogrammersareusedto theidea
thattheirapplication willbestarted by the user,
used and then terminated by the user. If the
application is restartedthenitisusually uptothe
usertoloadwhatevercontexttheyneed by way
of documents, etc. Sometimes an application
has to automatically retain state information
from run to run. For example, a game might
keep track of which level a player had
reached and the cumulative score, but this is
about as complicated as things get.
For an application running on a cell phone
things are altogether different. The actual
idea of the gadget implies that any
application could be hindered at any second
by an approaching call or the client settling
on a telephone decision. Somewhat this need
to make applications“interruptible” has been
taken up by cell phone working frameworks
as a more broad rule. Android, for instance,
will stop your application running since it
needs the memory or needs to save battery
life. It even ends and restarts your application
assuming a media reconfiguration is required.
Lifecycle Explorer
There is no more excellent method for feeling
alright with the lifecycle and its occasions
than to compose a short demo program that
shows you when they occur.
Start another Android Basic Activity project,
tolerating all defaults, call it Lifecycle and
afterward acknowledge every one of the
defaults to begin rapidly. In the Layout Editor
eliminate the“Hi World” string and spot a
TextView on the plan surface. Next resize it
so it fills the vast majority of the space and
eliminate its default text passage, ensure it is
obliged and has a huge wiggle room around
it:
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
textView.append( “Create\n”)
The remainder of the program essentially
abrogates every one of the occasion overseers
thus, calls the first occasion controller and
afterward adds an instant message to
textView:
abrogate fun onStart() { super.onStart()
textView.append(“Start\n”)
}
530
outState?.putCharSequence(“myText”,textView.text)
}
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
textView.append( “Create\n”)
if (savedInstanceState != null){
textView.text=savedInstanceState.getCharSequenc
e(“myText”)
}
This gets going in the typical manner
however presently we verify whether
savedInstanceState has any
information.Assuming that it does we recover
the put away text utilizing the key“myText”.
}
super.onRestoreInstanceState(savedInstanceState)
}
Do make sure to call the
super.onRestoreInstanceState assuming you
need the framework to reestablish the
remainder of the UI in the standard manner.
There are put and get techniques for a scope
of standard
Complex UI
Elements
One of the snares sitting tight for you is the
issue of precisely what is naturally saved and
reestablished.For instance,toward the
beginning of this part we had the narrative of
the application that lost the client’s structure
information when it was rotated.
Given what we presently know about the
auto-saving and reclamation of client
modifiable UI components, you may be
considering how this could occur? The
appropriate response is that the developers of
the application had presumably become used
to the programmed perseverance of UI state
and didn’t try to make sure that turn had no
impact. It had an impact in light of the fact
that the structure was being downloaded from
a site and showed in a WebView control. A
WebView control is persevered by the
framework, however it reloads the page when
it is reestablished. This implies that on a
revolution the structure was reloaded as
unfilled and the client’s information was lost.
Advanced State
Management
For fulfillment it is actually important that
there are a lot more ways to deal with
keeping up with state. Later you should find
how to store bunches of client information
locally for longer term determination, and
this is frequently enough to carry out state the
board however an arrangement change.
There are additionally further developed state
the executives issues when you come to
utilize Fragments,the subject of Android
Programming: Mastering Fragments and
Dialogs.For this situation you can utilize
retainedInstance to ask the framework not to
obliterate a whole Fragment. This implies
that every one of the information put away in
the Fragment is held despite the fact that the
Activity might be eliminated from memory.
This makes it conceivable to utilize a
Fragment as a store of state.
A definitive in getting sure that things going
as you need is to deal with the arrangement
change yourself. You can do this by rolling
out an
improvement to the show. Assuming you do
this then it is dependent upon you to roll out
the improvements required when the
onConfigurationChanged occasion
happens.You could,for instance,select to
quicken buttons and other UI objects into
new positions or simply disregard the need to
reconfigure altogether.
This is completely exceptional and for most
applications you can get by utilizing only the
onSaveInstanceState and
onRestoreInstanceState occasion handlers.
Summary
☐ Android, in the same way as other
versatile OSs, will eliminate your application
from memory and restart it as it needs to.
Chapter
14
Spinners
Working with Android Studio makes
assembling the UI simple with an intelligent
manager, the Layout Editor, yet you actually
need to discover how to deal with the things
it isn’t exactly so great at.In the following
two parts of our investigation of Android we
take a gander at spinners and pickers, the
subsequent stage up from buttons and text
controls.
</string-array>
The significance of the XML is self-evident
and this is the benefit of an intelligible
markup language.
Introducing the
ArrayAdapter
For the situation of UI gadgets that show
arrangements of things, Android has a
considerably more broad component to adapt
to the distinctive kind of things you could
show. Gadgets that show arrangements of
things by and large work with an illustration
of an“connector”.For additional on
connectors overall see Chapter 15.
A connector fundamentally takes a rundown
of items and converts them into something
that can be shown in the gadget. By and
large, you can make custom Adapters to do
shrewd things with arrangements of objects
of your own so they show properly. As a rule,
in any case, you can get by with simply
utilizing the gave worked in adapters.
this,
andRoid.R.layout.simple_spinner_dropdown _item, country)
Handling the
Selection
The following inquiry is, how would you find
that the client has made a selection?
The straightforward answer is that we need to
attach to the Spinner’s occasions and the
OnItemSelectedListener is the interface that
has the onNothingSelected and
onItemSelected occasion controllers. As the
interface characterizes two occasion
controllers it’s anything but a SAM thus we
need to utilize an object.
If you enter the accompanying line:
val onSpinner=object:AdapterView.OnItemSelectedListener{
You would then be able to utilize the right
snap Generate, Override Methods choice to
make a stub:
val onSpinner=object:AdapterView.OnItemSelectedListener{ supersede fun
onNothingSelected(p0: AdapterView<*>?) {
TODO(“not implemented”)
}
abrogate fun onItemSelected(p0: AdapterView<*>?,
p1: View?, p2: Int, p3: Long) { TODO(“not implemented”)
}
}
It additionally adds an import for
AdapterView.
You can see without a moment’s delay that
you need to carry out two occasion handlers:
textView.text=p2.toString()
}
spinner.onItemSelectedListener =
object:AdapterView.OnItemSelectedListener { supersede fun
onNothingSelected( p0:
AdapterView<*>?) {
abrogate fun onItemSelected( p0: AdapterView<*>?, p1: View?, p2: Int, p3:
Long) {
textView.text = p2.toString() }
}
If you currently run the program you will see
something like:
Creating an
ArrayAdapter from
a Resource
To make an ArrayAdapter from an asset you
want to utilize a static technique for the
ArrayAdapter class, createFromResource.
This simply needs you to determine the
specific situation, the asset id, and the
Spinner design. You should simply to
supplant the formation of
stringArrayAdapter:
spinner.adapter=ArrayAdapter.createFromResource(
this,
R.array.country
,
andRoid.R.layout.simple_spinner_dropdown_ item)
*resources.getStringArray(R.array.country))
spinner.adapter=ArrayAdapter<String>(
this,
andRoid.R.layout.simple_spinner_dropd own_item, country)
Chapter 15
Pickers
Android right now upholds three Pickers for
dates, times and general numbers and they are
significant ways of getting client input.
Notwithstanding, they have experienced such
countless amendments that they need
straightforward documentation or rules how
to utilize them. We should clear up the
confusion.
Working with
Pickers
☐ A picker is a“dial” that you can use to
choose one of a foreordained arrangement of
values.
In this sense it is a ton like the Spinner
shrouded in the past part, however one that
has a confined arrangement of choices.
There are two methods for utilizing a Picker,
as a gadget, or as a discourse box. You will
track down the TimePicker and the
DatePicker, prepared to put on the plan
surface, in the Date&Time part of the Palette.
The NumberPicker, notwithstanding, is a lot
of lower down, in the Advanced section:
Although now and again you likely will need
to make a Dialog box and should utilize a
perplexing DialogFragment to wrap the
Dialog and deal with its lifecycle, and there
are numerous circumstances where utilizing
the crude gadget will do the work alright. For
additional on DialogFragment see:
TimePicker
The TimePicker is an extremely simple
method for beginning. Assuming you make
another Android project, called
TimeAndDate and acknowledge each of the
defaults you can put a TimePicker,recorded
top of the Date and Time segment of the
Palette,on the plan surface very much like
some other gadget, and measure and find it as
required. In its default setup it shows in the
Layout Editor utilizing the style
android:timePickerStyle and has a simple
clock face and an info region that can be
utilized to establish the point in time by
hauling the hands on the clock face:
}
Now assuming you run the program you will
see the TextView change each time the client
adjusts the TimePicker by whatever method.
The full program, including the code for the
button and the occasion controller is shown
below:
supersede fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
timePicker.setIs24HourView(true) timePicker.currentMinute = 10
timePicker.currentHour = 13
+ timePicker.currentMinute.toString( }
timePicker.setOnTimeChangedListener { timePicker, h, m
- > textView.text = h.toString() + “:” + m.toString()
}
}
DatePicker
There are two date gadgets in the current
Android framework, DatePicker and
Calendar view. The DatePicker has been
being used since API 1 however Calendar
view was just presented in API 11. The
fundamental contrast between the two is the
way that they look. As they work similarly
and the DatePicker is more adaptable this is
the gadget we will utilize. Likewise whenever
you have encountered the manner in which
TimePicker works there is very little to add to
cover its date counterpart. To see the
DatePicker in real life essentially start
another task called Date and acknowledge the
defaults as a whole. Place a DatePicker on the
plan surface at the upper left-hand corner.
The DatePicker went through similar changes
with the presentation of Material Design as
did the TimePicker. However long you utilize
the most recent API and the default design it
will show in a schedule format:
Number Picker
You may be stressed that the NumberPicker
will be inconvenience when you notice that it
is in the Advanced part of the tool kit range!
Truly it is extremely simple to utilize, you
should simply choose it and spot it on the
plan surface. To give it a shot beginning
another venture called Number and
acknowledge the defaults in general.
Assuming you disapprove of the delivering of
the NumberPicker just disregard the mistakes
and construct the undertaking. The mistakes
should then go away.
If you run the app then you will see the
NumberPicker styled for the latest API which
in this case looks very odd because there is
nothing loaded into thespinner:
For example:
val values=arrayOf( “mike”,”sue”,”harry”)
numberPicker.maxValue=2 numberPicker.minValue=0
numberPicker.displayedValues=values
produces:
When it comes to recovering the information
you can utilize the getValue strategy,which
consistently returns a number. This is either
the record in the String cluster, or the genuine
worth assuming you are not utilizing a String
exhibit, of the thing the client picked.
NumberPicker picker,
int
oldVa
l, int
newV
al)
}
textView.text=values[new]
Notice anyway that this would come up short
assuming the rundown of things in the
NumberPicker had changed.
Multi-Digit Input
If you want to create a multi-digit input –for
hundreds, tens, units, say–then simply use
three NumberPickers. This is more interesting
than it initially shows up to powerfully follow
the current worth across more than one
NumberPicker. For instance, to construct a
three-digit input you first need to put three
NumberPickers on the plan surface with ids
numberPicker1, numberPicker2 and
numberPicker3.Place
numberPicker1onthefarleft, then
numberPicker 2 and thennumberPicker3.
Additionally add a TextView some place
convenient:
nps[i].maxValue=values.size-1
nps[i].minValue=0
nps[i].displayedValues=values
nps[i].setOnValueChangedListener(onValueCh
anged)
}
temp=““
for(i in nps.indices){
temp+=values[nps[i].value]
}
textView.text=temp
}
For this situation we don’t utilize any of the
occasion technique’s boundaries we just
utilize the qualities exhibit which is
accessible because of conclusion and query
the qualities that each NumberPicker is as of
now set to.
import
kotlinx.android.synthetic.main.activity_main.* import
kotlinx.android.synthetic.main.content_main.*
val values=Array(10,{i->i.toString()})
val nps=arrayOf(numberPicker1,numberPicker2,numberPicker3)
val onValueChanged= {picker:NumberPicker,old:Int,new:Int-> var temp=““
for(i in
nps.indices){
temp+=values
[nps[i].value]
}
textView.text=temp
}
for( I in
nps.indices){
nps[i].maxValue=values.size-1
nps[i].minValue=0
nps[i].displayedValues=values
nps[i].setOnValueChangedListener(onValueChanged)
}
Summary
☐ TimePicker, DatePicker and
NumberPicker give simple to utilize methods
of getting client input without utilizing an on-
screen keyboard.
Chapter
16
ListVie
w
ListView is presumably the most regularly
utilized UI part in an Android application. It
is easy to utilize, however you really want to
will grasps with the possibility of
an“connector”, and getting what is happening
pays dividends.
For a scope of reasons, one of the most
widely recognized things you really want to
do in an Android UI is to show a rundown of
things that the client can choose from. We
have as of now checked out the essential
Picker, however the ListView is a more broad
classification of“picker”. If you know about
work area advancement then you likely
consider records that the client can choose
from as being like a drop-down list. Android
and versatile gadgets frequently need more
than simply a little list. Because of the
restricted screen size, it is generally expected
the situation that the client must be shown an
outline of many various things. At the point
when the client chooses a thing they are then
given more subtleties of the thing, generally
called a subtleties view.
Displaying records and different assortments
of information is normal that Android has an
instrument that makes it more straightforward
once you see how it all works.
The key thought is that to show an
assortment, every thing in the assortment has
some way or another to be changed over to a
suitable View object.It is the View object that
the compartment shows for every thing of
information in the collection.
Understanding the
Adapter
Displaying an assortment of things has
various similitudes regardless the assortment
of things are, for sure holder is utilized. The
compartment has different places that are
noticeable on the screen for showing things.
For instance, a ListView has level openings,
one for each thing, and a GridView has a 2D
matrix of spaces. Every compartment
acknowledges a View article and shows it in
a space. For instance, you could give the
ListView TextView articles and it would
basically show text in every one of its slots.
You may be asking why not simply supply a
bunch of Strings to the ListView and let it
work out how to show the Strings as text?
Things could be coordinated along these lines
and it would be easier, however provided that
you needed to
Extending the
ListAdapter Class
Overall you need to take the ListAdapter
class and extend it to make your own custom
Adapter which produces a custom View
object for the holder to use in every one of its
spaces. The compartment requests the View
object to be utilized to show thing I or
utilizing whatever ordering suits the specific
holder. The Adapter returns the View object
and the holder shows it– without stressing
what it is for sure it compares to. This may
sound muddled, yet it ends up being
extremely straightforward in practice.
However, to make things significantly less
complex there is additionally an
ArrayAdapter which allows you to show a
solitary text thing for every component of a
variety of discretionary items. How can this
possibly work if the object in the array can be
anything? The first thing to point out is that
ArrayAdapter is a generic class and can
accept an array of any type as long as you
specify it when you create the ArrayAdapter
instance. The second highlight note is that
Array connector calls every thing’s toString
technique to get some text to show in the
holder, which is exceptionally basic yet in
addition extremely prohibitive. Truth be told,
it is very simple to alter what the
ArrayAdapter presentations, and this makes it
more flexible than you may expect and thus
certainly worth getting to know.
Using the
ArrayAdapter
Rather then, at that point, beginning with a
model that is totally broad, it merits taking a
gander at how the ArrayAdapter is utilized
related to a ListView.
Start another Android Studio project called
ListViewExample dependent on a Basic
Activity and acknowledge every one of the
defaults. For a basic model all we will do is
show a rundown of names in a ListView.
First delete the usual“Hello World” textView.
In the Layout Editor scroll down the Palette
until you can see the Containers and place a
ListView on the design surface. At the
moment the listView isn’t always
automatically assigned an id. If this is the
case type listView into the id in the Attributes
window. If you do this then a dummy content
will be generated for you:
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
this,
andRoid.R.layout.simple_list _item_1, myStringArray)
listView.setAdapter(myAdapter)
}
you will
arrayOf( “A”, “B”, “C”, “D”, “E”, “F”, “G”, “H”, “I”, “J”)
discover that you can automatically scroll
through the list using the usual flick gesture.
Get Selection
Perhaps the most important thing is to deal
with the user selecting an item. The usual
way of doing this is to write a handler for the
OnItemClickListener, which passes four
parameters:
onItemClick(AdapterView parent,View view,int position, long id)
The AdapterView is the complete View
displayed by the container, the View is the
View object the user selected, the position is
the position in
})
sets each item the user selects to“selected”.
this,
andRoid.R.layout.simple_list_ite m_1, myList)
A Custom Layout
So far we have just made use of the system
provided layout for the row. It is very easy to
create your own layout file and set it so that it
is used to render each row, but you need to
keep in mind that the only data that will be
displayed that is different on each row is
derived from the item’s toString method.
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView" />
this,
R.layout.mylay
out, myStringArray)
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width=“368dp”
android:layout_height=“wrap_cont ent”
android:descendantFocusability=“blocksDescendants”
android:orientation=“horizontal”
tools:layout_editor_absoluteX=“0dp” tools:layout_editor_absoluteY=“25
dp”>
<CheckBox
android:id=“@+id/checkBox2” android:layout_width=“wrap_content”
android:layout_height=“wrap_content” android:layout_weight=“1”
android:text=“CheckBox” />
<TextView
android:id=“@+id/textView”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content” android:layout_weight=“1”
android:text=“TextView” />
android:text=“TextView” />
<TextView
android:id=“@+id/textView2”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content” android:layout_weight=“1”
</LinearLayout>
R.layout.mylay out,
R.id.textView 2,
myStringArray )
to the
android:descendantFocusability= “blocksDescendants”
LinearLayout, or use the Property window to
set it to blocksDescendants:
With this change the event
handler should be called, but now you need to
keep in mind that the View object passed as
view in:
listView.setOnItemClickListener({ parent, view, position, id ->
id->
view.findViewById<TextView>(R.id.textVi ew).text=“Selected”
})
Notice that you can use findViewById in the
View that is returned.
A Custom
ArrayAdapter
If you only want to display a String in each
row you can use the standard ArrayAdapter
and the object’s toString method.You can
even customize the object’s toString method
to display something different from the
default, but it is still just a String.
If you have an array of general objects and
want to display multiple items from each
object, or items which are not Strings, then
you need to create a custom ArrayAdapter.
This isn’t difficult, although there are one or
two more advanced points to take note of.
For this first example, let’s keep it as simple
as possible. First we need some objects to
hold the data we are going to display– a
record type, say, with a field for name and
one for number in stock. You could also add
a photo of the item, but in the spirit of
keeping it simple a String and int are enough.
If you know other languages you might be
thinking that we need a struct or something
similar. In Java or Kotlin there are no structs.
If you want to create a record you create an
object with the necessary properties.
However Kotlin supports data classes which
are designed for the task and in many ways
are a superior “record” type to what you find
in other language.
Start a new project called CustomList and
accept all the defaults. Remove the default
text and add a ListView.
In Java it is a rule that every new class you
create has to be in a separate folder. You can
follow this convention in Kotlin but it is often
easier to add utility classes to the file you are
working in. You can always separate them at
a later date.
)
You might need to add more data than this to
try out the ListView properly but this at least
gets us started.
This looks
ArrayAdapter<MyData>(mycontext, resource, objects) {
complicated but it is the code you get using
Alt+Enter on the partially declared class. The
<out MyData> is the compiler protecting you
xmlns:android="http://schemas.android.com/apk/res/andr oid"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width=“368dp”
android:layout_height=“wrap_c ontent”
android:descendantFocusability=“blocksDescendants”
android:orientation=“horizontal”
tools:layout_editor_absoluteX=“0 dp”
tools:layout_editor_absoluteY= “25dp”
layout_height=“wrap_content” layout_width=“match_parent”>
<TextView android:id=“@+id/title”
android:layout_height=“wrap_content” android:layout_weight=“1”
android:layout_width=“wrap_content” android:text=“TextView” />
<TextView
android:id=“@+id/number”
android:layout_height=“wrap_content”
android:layout_weight=“1”
android:layout_width=“wrap_content”
android:text=“TextView” />
</LinearLayout>
Our first task is to get an inflater and inflate
the layout file:
val inflater=(mycontext as
Activity).layoutInflater val
row=inflater.inflate(resource, parent,false)
}
Now all we have to do is write some code
that makes use of the new class and this is
exactly the same as the code that made use of
the standard ListView:
val myAdapter=MyAdaptor(this,R.layout.mylayout,myDataArray)
listView.adapter=myAdapter
Don’t forget to put a ListView component on
the main layout:
} row=convertView
Notice that this is null safe as the compiler
checks that row gets a value one way or
another.
row.findViewById<TextVi
ew>(R.id.title),
row.findViewById<TextView>(R.id.number
)) row.tag=viewHolder
}
Notice that we have stored the references to
the TextViews in the viewHolder and stored
this in the row’s Tag field– this is what tag
fields are generally used for.
If we do have a recycled View object, we
need to get the viewHolder object:
} else {
row = convertView
}
ViewHolder).number.text =
objects?.get(position)?.myNum.toString()
return row
}
This
ArrayAdapter<MyData>(mycontext, resource, objects) {
constructor has two extra parameters used to
specify the id numbers of the two ViewText
objects in the layout. These are automatically
created properties of the class.
Finally we need to change the getView
method to use the two new private variables:
val viewHolder =ViewHolder (
row.findViewById<TextView>(res Title),
row.findViewById<TextView>(re sNumber))
R.layout.mylayou
t, R.id.title,
R.id.number,
myDataArray)
Custom Adapter
Putting together all the code introduced so far
gives:
class MyAdaptor(
val mycontext: Context?,
val resource: Int,
val resTitle: Int, val
resNumber: Int,
val objects: Array<out MyData>?):
} else {
row = convertView
}
Summary
☐ Containers like ListView work together
with an adapter to display data. ☐ The
adapter accepts a data structure– usually an
array or a list– and converts any data item
into a View object that represents the data. ☐
You can handle a selection event to find out
what the user has selected.
☐ The View object can be complex with an
outer container and any number of child
objects.
☐ The basic ArrayAdapter uses each object’s
toString method to provide the data to display
in a ViewText object.
Chapter 17
Android The Kotlin
Way
After seeing Kotlin at work making your
Android code shorter and, more importantly,
clearer, it is time to gather the ideas together.
This chapter is a collection of the ways Kotlin
makes Android easier in comparison with
Java. If you are not a Java programmer many
of these differences will not seem impressive.
This chapter is at the end of the book because
it can serve as a reminder to a Java
programmer learning Android what a
difference Kotlin makes. It could also be read
first by a fairly experienced Android
programmer wanting to know what their
Android Java idioms look like in Kotlin.
If you want a good grounding in Kotlin I can
do no better than recommend my own
Programmer’s Guide To Kotlin ISBN 978-
1871962536.This chapter is more about how
Kotlin affects your approach to Android
programming than a general Kotlin tutorial.
What You No
Longer Have To
Type
☐ Semicolons, type specifiers and new
The first joy of Kotlin is that you no longer
have to type a semicolon to mark the end of
each line. You can type a semicolon if you
want to and Android Studio doesn’t mark it
as an error, but it does suggest that you might
want to remove it:
578
View Objects As
Properties
In Java finding a View object uses the
findViewById method, and this is still needed
in Kotlin in many cases. It is even easier to
use in Kotlin because it is implemented as a
generic extension function and you can avoid
having to cast to the correct type:
val button = findViewById<Button>(R.id.my_button)
Event Handlers
With the whole of Chapter 4 about event
handling, only a brief summary is given here.
In Java event handlers are methods that
belong to event listener objects often defined
using an interface. In many cases there is a
single event handler defined in a single
interface and this is a SAM– Single Abstract
Event.
For example the View.OnClickListener
interface is defined as:
public interface OnClickListener { void
onClick(View var1);
}
onActionItemClicked(
mode: ActionMode?, item: MenuItem?): Boolean { TODO(“not
implemented”)
}
override fun onCreateActionMode(
mode: ActionMode?, menu: Menu?): Boolean { TODO(“not implemented”)
}
}
The same approach works if the event listener
is defined as a class with
Data
Kotlin essentially reuses Java’s data types
including arrays and strings, but it augments
them and has its own approach to them.
However, essentially a Kotlin array is a Java
array and a Kotlin String is a Java String.
You create an array using:
var a=arrayOf(1,2,3)
which creates an array of three
integers. For larger arrays you can
use:
var array=Array(size, initializer)
where size gives the number of elements and
initializer is a lambda expression that used to
initialize the array.For example:
var a = Array(1000, { i -> i * 2 })
If you want the equivalent of an ArrayList in
Java use List or MutableList. Kotlin’s Strings
are much like Java’s but it is worth knowing
that they support templating.For example:
var s = “Name $name and Address $address”
will insert the values of the variables– name
and address– into the string. Although Kotlin
doesn’t have a record or structure type, it
does have data classes.If you create a class
with a primary constructor something like:
class MyPersonClass{
var name:String=““
var age:Int=0
}
then you get a class with two properties
initialized as
specified. If you also add the modifier “data”
in front:
data class MyPersonClass{ var
name:String=““
var age:Int=0
}
you also get some auto-generated methods
including, equals, copy, hashcode, toString
and componentN. The componentN methods
are particularly useful as they provide
destructuring:
var myDataObject=MyDataClass(“Mickey”,89)
var (myName,myAge) = myDataObject
Null Safety
Perhaps one of the most subtle features of
Kotlin you have to get to know and use is its
null safety.
References can be either non-nullable or
nullable.
If you declare a variable in the usual way you
get a non-nullable: var myVariable:sometype= something
and you cannot set the variable to null
because:
myVariable=null
throws a compiler error.
The compiler tracks operations that could
generate a null, and flags any operation that
could possibly set a non-nullable variable to
null. For example, if a function could return a
null you cannot assign it to a nonnullable.
This often occurs if you are trying to use a
Java function which, of course,doesn’t
support non-nullable types.
If you need a nullable reference then you
have to explicitly declare it using ?
as in:
var myVariable:sometype?=something
Now myVariable can be set to null:
myVariable=null
and this works without a compiler error or
warning.
Index
2D sprite
...................................................................
235
activity
bar.............................................................
180
Activity.....................................................
20, 33, 165
activity_main.xml....................................
adapter......................................................
AdapterView............................................
Add New
Resource...................................................
addView....................................................
171, 173 arrangement tool
...................................................................
142 all
attributes..................................................
105 alpha
channel......................................................
Alt+Enter
...................................................................
Android
graphics....................................................
223 android
namespace................................................
288 Android
Studio........................................................
310 Android Studio welcome
screen..............................................
Android
Timer........................................................
242 android:onClick
...................................................................
188
animation..................................................
234 mysterious
function.....................................................
92, 304
AntiAlias...................................................
235
AppCompat..............................................
AppCompatActivity................................
Array................................................
ArrayAdapter..........................................
259, 262, 284, 288 arrayOf
...................................................................
as?.............................................................
308 Aspect Ratio
Constraint................................................
Attributes.................................................
161 Attributes
window....................24-25, 42-
44, 52, 61, 75, 100, 108-110,
117, 130-132, 139, 153, 161-
162, 174, 205-209, 256-257,
267, 283
autocompletion........................................
auto-
sizing.........................................................
Autoconnect.............................................
136 autogenerated id
...................................................................
in reverse
compatibility............................................
Barrier......................................................
gauge
alignment..................................................
pattern
constraint..................................................
Basic
Activity.............................................
181
bias............................................................
Bitmap......................................................
223-225
blocksDescendants...................................
290
blueprint...................................................
Bounce ball
example.....................................................
breakpoint................................................
Bundle.......................................................
249
Button..............................................
56, 99
Calculator App
...................................................................
Callback
object........................................................
200
Canvas......................................................
225, 226 Canvas methods
...................................................................
226
cast............................................................
46, 260, 262 chain
icon............................................................
chains..............................................
156
CheckBox.................................................
109 kid
object........................................................
class...........................................................
304, 306 clear
constraint..................................................
138
clipping.....................................................
cutting properties
...................................................................
closure.......................................................
91-93
Color.........................................................
212 Component
Tree.........................................19,
25, 65, 81, 125, 136, 159, 180
componentN.............................................
contingent
resources...................................................
221
Constraint................................................
161 imperative lines
...................................................................
ConstraintLayout...................................4
115-116, 124, 133-135, 144, 161
consumed
...................................................................
container
...................................................................
281
content_main.xml....................................
20, 27
ContextMenuInfo....................................
198 Convert to
ConstraintLayout
...................................................................
136 convertView
...................................................................
295 coordinate
system.......................................................
233
count.........................................................
createFromResource
...................................................................
Custom Locale
app...................................................
CustomList...............................................
information
class...........................................................
306
DatePicker................................................
default margin
...................................................................
erase
constraint..................................................
thickness free
pixel...........................................................
plan
surface......................................................
41, 56
destructuring...................................
Device In Editor
...................................................................
Dimension.................................................
dp (thickness autonomous
pixels)........................................................
drawable
folder.........................................................
Drawables.................................................
221 drawBitmap
...................................................................
Eclipse
IDE............................................................
11 Edit
Translations.............................................
EditorInfo.................................................
EditText
control.......................................................
Elvis
operator....................................................
Emulator..................................................
occasion
handler......................................................
44, 48, 83, 304 occasion
listener
...................................................................
Events in
Java..................................................
83 exception
...................................................................
findItem....................................................
findViewById...........................................
291, 294, 304 Fragment
...................................................................
FrameLayout...........................................
122, 124, 133 capacity
reference
operator....................................................
304
generics.....................................................
260, 282, 284
getChildAt........................................
getChildCount
...................................................................
getter.........................................................
302
gettype......................................................
gone...........................................................
Google Play
...................................................................
gravity.......................................................
133
GridLayout..............................................
116
GridView..................................................
group.........................................................
179
guideline...................................................
158 Guidelines
tool............................................................
Hardware Keyboard Present
option
.................................................................
105
HAXM......................................................
height........................................................
128 Holo
theme...............................................
266 even
bias............................................................
ic_menu_add............................................
102 iCalc
example.....................................................
251 id
property....................................................
212 IDE – Integrated
Development
Environment............................................
ImageButton............................................
ImageView control
...................................................................
IME (Input Method Editor)
...................................................................
immutable................................................
308 import
statements.................................................
74, 166 Include Kotlin
support......................................................
Infer
Constraints...............................................
136, 140
inflater......................................................
176, 187, 293
inheritance................................................
inputType
property....................................................
introducing Android
Studio..............................................
interface....................................................
85
item...........................................................
180
item.getMenuInfo()..................................
198
ItemId.......................................................
Java...........................................................
94 Java unknown class
...................................................................
java folder
...................................................................
Java
lambdas...........................................
Java or Kotlin
...................................................................
Java
String........................................................
Java
Types.........................................................
Kotlin
...................................................................
Kotlin String
...................................................................
lambda......................................................
90, 103 Landscape option
...................................................................
layout
...................................................................
Layout containers
...................................................................
Layout
Editor....................................18,
21, 62, 116, 162, 174, 246, 255,
283
layout_height............................................
154 layout_margin
properties.................................................
layout_weight...........................................
layout_width............................................
154
LayoutInflater..........................................
LayoutParams..........................................
171, 176
let...............................................................
309 life
cycle..........................................................
244 life cycle
events........................................................
251 Lifecycle
example.....................................................
250 lifetime
...................................................................
243
LinearLayout...........................................
124-125, 133, 145, 168, 169
ListAdapter
...................................................................
28 2
ListView....................................................
283 ListView
example.....................................................
290 Local
functions...................................................
locale.........................................................
216, 219
localization...............................................
218-219 long
click...........................................................
195
MainActivity............................................
34-35
manifest....................................................
252 Manual
Constraints...............................................
Margin
Offsets.......................................................
margins
...................................................................
Match Constraints
...................................................................
154-155
match_parent...........................................
matrix
...................................................................
MeasuredHeight
...................................................................
MeasuredWidth.......................................
menu.........................................................
179, 208 menu asset file
...................................................................
Menu
Tree...........................................................
menu_main.xml
...................................................................
MenuInflater............................................
MenuItem.................................................
187
MenuSample............................................
methods....................................................
mutable.....................................................
mutator.....................................................
303 myAdapter
...................................................................
294
settled LinearLayouts
...................................................................
124 nesting
...................................................................
New, Resource
File............................................................
217, 221 non-
nullable.....................................................
307
notifyDataSetChange..............................
262
nullable.....................................................
307
NumberPicker..........................................
272 NumberPicker
example.....................................................
272
object........................................................
object
instantiation.............................................
onClick
...................................................................
OnClickListener......................................
onConfigurationChanged
...................................................................
252
onContextItemSelected...........................
198
onCreate...................................................
35, 245, 248, 250
onCreateContextMenu
...................................................................
195
onCreateOptionsMenu............................
187
OnDateChanged......................................
271 onDestroy
...................................................................
245 onEditorAction
...................................................................
108
onPrepareOptionsMenu.........................
189
onResetoreInstanceState.........................
250
onRestart..................................................
245
onResume.................................................
248 onResume and
onPause...........................................
245
onSaveInstanceState................................
250 onStart and
onStop.......................................................
244 OnTimeChanged
...................................................................
268
opacity......................................................
orientation
...................................................................
bundle
level...........................................................
Packed......................................................
149
padding,...........................................
133
Paint..........................................................
226
Palette.......................................................
39, 255 Parcelable
interface....................................................
251 enduring
data...........................................................
pixel-based
units..........................................................
positioning................................................
Project
window......................................................
71
properties........................................
pt
(point).......................................................
qualifier....................................................
302
R
object........................................................
213, 221
R.id............................................................
R.layout.activity_main
...................................................................
RadioButton
...................................................................
RadioGroup.....................................
RelativeLayout.........................................
128, 133
removeView..............................................
removeViewAt
...................................................................
goal, issue
of................................................................
resource....................................................
asset (res)
folder.........................................................
36 Resource editor
...................................................................
asset
id................................................................
288 Asset
window......................................................
102, 256
resources...................................................
256, 262 Resources object
...................................................................
Run
...................................................................
Runnable..................................................
238
runOnUIThread......................................
242
SAM..........................................................
87-88, 238, 304
save............................................................
savedInstanceState..................................
screen sizes
...................................................................
semicolons................................................
301
setContentView........................................
36, 166
setOnClickListener..................................
setter
...................................................................
showAsAction..........................................
signature
...................................................................
Single Abstract
Method......................................................
238 estimating a
component................................................
sliders........................................................
Spinner.....................................................
282 Spread
Inside........................................................
spread administrator
*.................................................................
sprite-based
graphics....................................................
src (source)
property....................................................
102
state...........................................................
249 String
array.........................................................
String cluster
resource....................................................
string
resources...................................................
stroke
...................................................................
super.onRestoreInstanceState................
251
Switches....................................................
110, 113
TableLayout
...................................................................
tag fields
...................................................................
templating................................................
Text
Field..........................................................
105
TextView..................................................
41, 78, 99, 288
this.............................................................
thread..............................................
threading..................................................
three-spot
icon............................................................
183, 256
TimePicker...............................................
267 Timer
object........................................................
TimerTask................................................
Toggle
Button.......................................................
110, 113
Toolbar.....................................................
180-182 top-
level.................................................
toString()
...................................................................
following
qualifier....................................................
302
transform..................................................
change
matrix.......................................................
change
sequence....................................................
232 Translation
Editor........................................................
221 Translation
Tools..........................................................
type..................................................
type
projection.................................................
type
qualifier....................................................
302 type specifiers
...................................................................
301
UI
...................................................................
165 UI
thread........................................................
fix order, Ctrl-
Z,...............................................................
units..........................................................
118
val..............................................................
values........................................................
211
var.............................................................
vertical
bias............................................................
143
View..........................................................
36, 48, 115, 165 View
hierarchy..................................................
171 View
objects.......................................................
ViewGroup.......................................
168, 173, 175
ViewHolder..............................................
Visual Basic
...................................................................
Widgets.....................................................
width.........................................................
128
wrap_content...........................................
154, 157
XML..........................................................
178 xmlns
attribute....................................................
288
@......................................................
@+.............................................................
@+id..........................................................
179
*.................................................................