问题
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.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/14663449/use-androidonclick-with-methods-from-another-activity