简体   繁体   English

另一个类的android xml按钮调用方法

[英]android xml button call method of another class

I have my xml set up so that each class includes the same menu bar. 我设置了xml,以便每个类都包含相同的菜单栏。 I have to duplicate each method that is called by a button onClick in every class that uses the menu bar though. 我必须在每个使用菜单栏的类中复制每个按钮onClick调用的方法。 Is there a way around this? 有没有解决的办法? I tried to extend the other class, but every class already extends activity and you cannot extend multiple classes in Android. 我尝试扩展其他类,但是每个类都已经扩展了活动,并且您不能在Android中扩展多个类。

Example: menu bar has button doStuff. 示例:菜单栏具有按钮doStuff。 class A includes menu bar. A类包括菜单栏。 Class A implements doStuff. A类实现doStuff。 class B includes menu bar. B类包括菜单栏。 Class B implements doStuff. B类实现doStuff。

They are both implementing the same method in exactly the same way. 他们俩都以完全相同的方式实现相同的方法。 Is there a way to define these methods (like doStuff) once and have each button call that method? 有没有一种方法可以一次定义这些方法(如doStuff),并让每个按钮调用该方法?

My solution was to make each button call a method. 我的解决方案是使每个按钮调用一个方法。 This was repeated in all classes that used buttons. 在所有使用按钮的类中都重复了这一步骤。 Then these individual methods called a central one, so that the code could be changed from one location, rather then having to repeat changes. 然后,这些单独的方法称为中央方法,因此可以从一个位置更改代码,而不必重复更改。

Example: menu bar has button doStuff. 示例:菜单栏具有按钮doStuff。 class A includes menu bar. A类包括菜单栏。 Class A implements doStuff. A类实现doStuff。 class B includes menu bar. B类包括菜单栏。 Class B implements doStuff. B类实现doStuff。

Solution: menu bar has button doStuff. 解决方案:菜单栏上有按钮doStuff。 class A includes menu bar. A类包括菜单栏。 Class A implements handler that refers the call to a central class. 类A实现了将调用引用到中心类的处理程序。 class B includes menu bar. B类包括菜单栏。 Class B implements the handler. B类实现处理程序。

You can create another class which implements doStuff() method, and then only set listeners for buttons in every class. 您可以创建另一个实现doStuff()方法的类,然后仅在每个类中为按钮设置侦听器。 You will always have to set listeners, either by calling setOnClickListener() (or in XML file, but then I don't know if you can call another classes method). 您将始终必须通过调用setOnClickListener() (或在XML文件中setOnClickListener()来设置侦听器,但是我不知道是否可以调用另一个类方法。 If you need some views from your class, you can then pass them as parameters. 如果您需要类中的某些视图,则可以将其作为参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM