Any widget (control) in Android is inherited from the base View class. In turn, each View can be assigned an identifier (hereinafter referred to as ID ).
<Button android:id="@+id/my_button" .... />
ID are usually assigned in xml and are used to find controls in the current tree of all View.
Button myButton = (Button) findViewById(R.id.my_button);
Detection of a click ( click ) on any View (not necessarily a Button ) occurs through the means of implementing the View.OnClickListener interface. This can be done in two ways: by implementing this interface Activity or creating an instance of an anonymous class ( new View.OnClickListener() ). But the main thing that needs to be done is to override the OnClick() method of the OnClick() interface. Yes, and do not forget that you need to assign the necessary control to his listener ( view.setOnClickListener(onClickListener) ). In addition, one listener can be assigned to any number of controls.
How to distinguish which View was clicked? Just look at the signature of the onClick method of the onClick interface:
public abstract void onClick (View v){}
Inside this method, developers allow us to use the link to the View that was clicked (in this case, View v ). It remains only to distinguish different views according to their individual characteristics. Here the ID comes to the rescue. The view.getId () method returns us the value of the identifier of the specific control. It remains only to match it.
@Override public void onClick(View v) { switch (v.getId()) { case R.id.my_button1: //Π²ΡΠΏΠΎΠ»Π½ΡΠ΅ΠΌ Π½Π΅ΠΎΠ±Ρ
ΠΎΠ΄ΠΈΠΌΠΎΠ΅ Π΄Π΅ΠΉΡΡΠ²ΠΈΠ΅ break; // Π²ΡΠ·ΡΠ²Π°Π΅ΡΡΡ Π΄Π»Ρ Π²ΡΡ
ΠΎΠ΄Π° ΠΈΠ· Π±Π»ΠΎΠΊΠ° switch (ΠΏΡΠΈ Π²ΡΠ·ΠΎΠ²Π΅ Π΄Π°Π»ΡΠ½Π΅ΠΉΡΠΈΠΉ ΠΊΠΎΠ΄ Π½Π΅ ΠΈΡΠΏΠΎΠ»Π½ΡΠ΅ΡΡΡ) case R.id.my_button2: //Π²ΡΠΏΠΎΠ»Π½ΡΠ΅ΠΌ Π½Π΅ΠΎΠ±Ρ
ΠΎΠ΄ΠΈΠΌΠΎΠ΅ Π΄Π΅ΠΉΡΡΠ²ΠΈΠ΅ break; case R.id.my_button3: //Π²ΡΠΏΠΎΠ»Π½ΡΠ΅ΠΌ Π½Π΅ΠΎΠ±Ρ
ΠΎΠ΄ΠΈΠΌΠΎΠ΅ Π΄Π΅ΠΉΡΡΠ²ΠΈΠ΅ break; case R.id.my_button4: //Π²ΡΠΏΠΎΠ»Π½ΡΠ΅ΠΌ Π½Π΅ΠΎΠ±Ρ
ΠΎΠ΄ΠΈΠΌΠΎΠ΅ Π΄Π΅ΠΉΡΡΠ²ΠΈΠ΅ break; } }
ps. It should be noted that for the system ID is a value of type int.
pps. There is 1 more way to detect depression by directly calling the method:
<Button android:onClick="method" ... />
In this case, the specified method is simply called. Read more about this option here.