CircuitScholar CircuitScholar - 2 months ago 20
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:

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
defaults to the main activity's
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,
). 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()


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.