使用android:onClick与其他活动中的方法? [英] use android:onClick with methods from another activity?

查看:98
本文介绍了使用android:onClick与其他活动中的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的活动中包含菜单xml,我使用onClick属性而不是在每个startActivity上进行绑定.

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

我的问题是,如何在xml onClick attr上定义以调用例如位于mainActivity上的方法?

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

我想到了类似android:onClick ="mainActivity.doSomething"的东西,但是它不起作用.

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

推荐答案

在xml中使用onclick是

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:

startActivity:

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

mainActivity:

mainActivity:

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

startActivity.xml:

startActivity.xml:

android:onClick="callOtherMethod" 

除非您可以获得目标方法Activity的实例,否则您的doStuff方法也必须是静态的.

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

这篇关于使用android:onClick与其他活动中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆