1

I have menu xml which included in my activities, im using onClick attribute instead of binding on every startActivity.

My question is, how can I define on the xml onClick attr to call methods which is located on my mainActivity for example?

I thought about something like android:onClick="mainActivity.doSomething" but its doesnt work.

Idan Gozlan
  • 3,173
  • 3
  • 30
  • 47

2 Answers2

5

Using onclick in xml is a bad idea. The fact is it only tries to find the method that the current class is in which is using it. One way to do this IF you really want to do it this way is:

startActivity:

public void callOtherMethod(){
   mainActivity.doStuff();
}

mainActivity:

public static void doStuff(){
//dosomething.
}

startActivity.xml:

android:onClick="callOtherMethod" 

Your doStuff method must also be static, unless you can get a instance of the target method Activity.

Community
  • 1
  • 1
wtsang02
  • 18,603
  • 10
  • 49
  • 67
  • 1
    I don't agree on your statement, that using onclick in xml is generally a bad idea. The reasons given in the answer you linked are rather weak. You have to be aware of all the things mentioned there but it works fine and can help to keep your code short. Rather a matter of taste than anything else. – pumpkee Feb 02 '13 at 16:16
1

I thought about something like android:onClick="mainActivity.doSomething" but its doesnt work.

It's normal, Android looks for the onClick method declared in the xml layout only in the current activity where that layout file is used(and it wouldn't make sense anyway to look in other activities as those activities could be well destroyed when you call that method).

My question is, how can I define on the xml onClick attr to call methods which is located on my mainActivity for example?

You should explain what you're trying to do. Accessing methods of an Activity from another Activity should be avoided, it's not the proper way of doing things in Android.

user
  • 86,916
  • 18
  • 197
  • 190