简体   繁体   English

Android 中的“一般”功能放在哪里?

[英]Where to put "general" functions in Android?

I want to write a general function for my project that will be used across many different files and I don't want to have it in a particular class.我想为我的项目编写一个通用的 function,它将在许多不同的文件中使用,我不想将它放在特定的 class 中。

Where am I supposed to put it?我应该把它放在哪里?
Inside a new package as a class?在新的 package 中作为 class?

Is this the only option?这是唯一的选择吗?

Create a new package as util and create all common methods in there, for example:创建一个新的 package 作为 util 并在其中创建所有常用方法,例如:

Create package as com.xyz.util .创建 package 为com.xyz.util

Create a class as Util in above package.在上面的package中创建一个class作为Util

Then write your all common methods in this Util class.然后在这个Util class中写下你所有常用的方法。

You can write static methods in this class and access them as Util.method_name();你可以在这个 class 中编写 static 个方法,并以Util.method_name(); . .

In Java every method lives in a class. So yes, its the only option.在 Java 中,每个方法都存在于 class 中。所以是的,它是唯一的选择。 A common approach is to use a utility class containing only static methods.一种常见的方法是使用仅包含 static 方法的实用程序 class。 You can use it from everywhere without creating any instances.您可以在任何地方使用它而无需创建任何实例。

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

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