简体   繁体   English

使功能(在活动中使用时执行相同功能的特定视图)在 Android (Java) 中通用

[英]Making a function (A particular view to perform same function when used in activities) universal in Android (Java)

I have been recently thinking about, how can I make my code more efficient?我最近一直在思考,我怎样才能让我的代码更有效率? I have a Floating Action Button which does a common task when clicked on.我有一个浮动操作按钮,单击时会执行一项常见任务。 I want this button to be present in all activities.我希望这个按钮出现在所有活动中。 When pressed this FAB button it opens a circular menu ( https://github.com/Ramotion/circle-menu-android ) wherein I can open any activity I click on.当按下这个 FAB 按钮时,它会打开一个圆形菜单 ( https://github.com/Ramotion/circle-menu-android ),我可以在其中打开我点击的任何活动。 I do not want to pass any reference to another activity I just want to start that activity.我不想传递对另一个活动的任何引用,我只想开始该活动。 Now in order to achieve this what I currently do is declare the FAB button and write same piece of code over and over again in all the activities I want to use this button in. My question is how can avoid repetition of the same piece of code and get my work done more easily.现在为了实现这一点,我目前所做的是声明 FAB 按钮并在我想在其中使用此按钮的所有活动中一遍又一遍地编写相同的代码段。我的问题是如何避免重复相同的代码段并更轻松地完成我的工作。 Is there a way I can globally declare a function and call it in onclicklistener method in all the activities?有没有办法可以全局声明一个函数并在所有活动的 onclicklistener 方法中调用它? Thank You谢谢

OnClickListener is a class. OnClickListener 是一个类。 Just create a subclass that does what you want, and pass an instance of that to setOnClickListener.只需创建一个可以执行您想要的操作的子类,然后将其实例传递给 setOnClickListener。

Or if you really never want to do anything else, subclass FAB and override its constructor to set the onClickListener with a listener that does what you want.或者,如果您真的不想做任何其他事情,请将 FAB 子类化并覆盖其构造函数以使用执行您想要的监听器的监听器设置 onClickListener。 Then use that subclass instead of the base FAB class in your xml.然后在您的 xml 中使用该子类而不是基 FAB 类。

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

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