简体   繁体   中英

android xml button call method of another class

I have my xml set up so that each class includes the same menu bar. I have to duplicate each method that is called by a button onClick in every class that uses the menu bar though. 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.

Example: menu bar has button doStuff. class A includes menu bar. Class A implements doStuff. class B includes menu bar. Class B implements 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?

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. class A includes menu bar. Class A implements doStuff. class B includes menu bar. Class B implements doStuff.

Solution: menu bar has button doStuff. class A includes menu bar. Class A implements handler that refers the call to a central class. class B includes menu bar. Class B implements the handler.

You can create another class which implements doStuff() method, and then only set listeners for buttons in every class. 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). If you need some views from your class, you can then pass them as parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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