CircuitScholar CircuitScholar - 27 days ago 13
Android Question

Android: Specify full method path in android:onClick

This question is about Android development. In general, how do you tie a layout XML file to a certain Activity java file? This is relevant in a case such as a button with the android:onClick attribute specified. Suppose you have a layout XML file with a button like the following:

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />


So when this button is clicked, a
sendMessage(View view)
method is called. If more than one Activity has a
sendMessage(View view)
method, how does Android decide which one to call? There's literally absolutely nothing associating layout files with Activity files. In Android Studio, I've found that the
android:onClick="sendMessage"
defaults to the main activity's
sendMessage
method if there is more than one choice. I've also found that Android Studio doesn't let you simply specify the full method path (for example,
android:onClick="com.example.Activity2.sendMessage"
). Am I missing something?

Edit: I would like to add that Android Studio shows the sendMessage defaulting to a specific activity, REGARDLESS of which Activities have specified the layout via setContentView()

Answer

The android:onClick will call the method on the Activity your layout is inflated and attached to. There should be no tight coupling between a layout and it's controller, so thats why you can't specify a "full path".

I'd recommend using a programatical OnClickListener instead of the xml attribute. It gives you much greater control.

Comments