Pro Android with Kotlin



Yüklə 4,6 Kb.
Pdf görüntüsü
səhifə15/231
tarix29.11.2023
ölçüsü4,6 Kb.
#138831
1   ...   11   12   13   14   15   16   17   18   ...   231
@de android telegram Pro Android with Kotlin Developing Modern Mobile

xxii
Introduction
final EditText et = findViewById(R.id.edit);
final Button btn = findViewById(R.id.btn);
final TextView text = findViewById(R.id.text);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String entered = et.getText().toString();
text.setText("You entered '" + entered +
"' and pressed 'Go'");
}
});
}
}
Here are a few notes about the previous Java code:
 
The 
public
in front of the class says that it is visible from everywhere.
It cannot be omitted here since otherwise the framework could not use 
the class.
 
The 
setContentView()
changes something by virtue of the “set,” 
which is such a common construct that you might want to write it 
more concisely as 
contentView = s.th.
instead, even with a variable 
of name "contentView" not actually existing or being private. A couple 
of competitor languages allow for this type of syntax. In Groovy for 
example, you can write contentView = s.th.and the language will 
internally translate it to 
setContentView()
.
 
The 
final
in front of the three declarations is necessary in Java up to 
version 7 because the variables are going to be used in the anonymous 
inner class that comes a little later.
 
Also, for the 
setOnClickListener()
method, you might want to use 
.onClickListener = s.th.
instead. It’s the same for the 
.setText()

little later.
 
The argument to 
setOnClick-Listener()
is an object of an anonymous 
inner class; it is already an abbreviation of first declaring and then 
instantiating and using it. But you could be even more expressive with 
syntax like 
btn -> do s.th.
or similar, just not in the Java language 
(well, at least not before Java 8).
 
For the 
et.getText()
method, you could just as well write something 
like 
et.text
, which would express the same thing but is shorter.
A sister project that does the same thing but with Kotlin support is written in the Kotlin 
language as follows:
package de.pspaeth.simplekotlin
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*



Yüklə 4,6 Kb.

Dostları ilə paylaş:
1   ...   11   12   13   14   15   16   17   18   ...   231




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©genderi.org 2024
rəhbərliyinə müraciət

    Ana səhifə