use android:onClick with methods from another activity?

不打扰是莪最后的温柔 提交于 2019-12-08 03:12:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!