has an interface specified, but there is no implementation of the methods of this interface. Let's fix this with Eclipse. Hover over MainAcivity and select Add unimplemented methods
Eclipse will add the familiar onClick method. Only now this method will be implemented in the Activity, and not in a separate handler object. Accordingly, the Activity will act as a handler.
Fill in the method exactly as before. Nothing has changed. It is also served the View (on which the event occurred) as input. We will use the Id to determine which View it is and perform the corresponding actions:
1
2
3
4
5
6
7
8
9
10
11
12
13
public void onClick(View v) {
//by id , we determine the button that called this
switch (v) handler.getId()) {
case R. id. btnOk:
/ / кнопка OK button
TVout.setText("OK button pressed);
break;
case R. id. btnCancel:
/ / кнопкаCancel button
TVout. setText("Нажата кнопкаCancel " button is pressed);
break;
}
}
All that remains onCreateis to assign a handler to the buttons in the onCreate method. This will be the this object, i.e. the current MainActivity object.
1
2
btnOk.setOnClickListener(this);
btnCancel.setOnClickListener(this);
With this implementation, we did not create any extra objects (the Activity is created anyway) and the memory consumption is minimal, this is the recommended method. But this method may seem complicated and incomprehensible, especially if you have little experience in object-oriented programming. In this case, use the implementation that you understand and are comfortable with. And with time and experience, understanding will definitely come.
Full Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class MainActivity extends Activity implements OnClickListener {