Using On Click Listeners in Kotlin
In Java, setting an onClickListener usually follows a familiar Android pattern, anonymous classes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "i've been clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
In Java 8 which can be used when jack is enabled, the anonymous class can be replaced with a lambda
1
2
3
4
5
6
7
8
9
10
11
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(view -> Toast.makeText(MainActivity.this, "i've been clicked", Toast.LENGTH_SHORT).show());
}
}
In Kotlin it is very similar. An onClickListener can be set as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById(R.id.button) as Button
button.setOnClickListener(object: View.OnClickListener {
override fun onClick(view: View?) {
Toast.makeText(this@MainActivity, "i've been clicked", Toast.LENGTH_SHORT).show()
}
})
}
}
Or can be set with a lambda:
1
2
3
4
5
6
7
8
9
10
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById(R.id.button) as Button
button.setOnClickListener { Toast.makeText(this@MainActivity, "i've been clicked", Toast.LENGTH_SHORT).show() }
}
}
And we can also use a lambda with an argument:
1
2
val button = findViewById(R.id.button) as Button
button.setOnClickListener {view -> doSomething(view)}
And that’s pretty much all there is to it for setting an onClickListener in Kotlin