Android的,最好的方式提供应用程序特定的常量库项目?最好的、常量、应用程序、方式

2023-09-05 06:05:37 作者:月下独酌

我创建一个库项目为多家Android应用程序中。 这些应用都有,我想包括在库项目,但该库项目功能要求使用特定应用常数一些常用的功能

I am creating a library project for a number of android apps. The apps all have some common functionality that I wish to include in the library project but the library project functions require use of application specific constants

所以我在寻找一种方式来提供的库函数与常量的名称,并允许每个应用程序定义它们

So I am looking for a way to provide the library functions with the names of the constants and allow each app to define them

一个特定的应用程序不变的一个例子,它是如何在库项目中使用

An example of a specific app constant and how it is used within the library project

public class AppConstants {
    public static final long APP_ID = 6;//Needs to be set for each app
}

public static long getCurrentAppId(Context context) {
    return getLongPreference(context, CURRENT_APP_ID_KEY, AppConstants.APP_ID);
}

这是大约60常数需要被定义为每个应用程序进行了大量的库函数只是一个例子

This is just one example of approximately 60 constants that need to be defined for each app for a large number of library functions

很显然,我通常只导入/包括项目的具体app_constants.java文件,但是这是不可能的,在库项目的文件,因为它没有得到一个线索具体的应用程序(这是正确的)

Obviously I would normally just import/include the project specific app_constants.java file but this is not possible in the library project files as it hasn't got a clue about the specific applications (rightly so)

那么,什么是让每个特定应用程序重写常数的最佳方法是什么?

So what is the best way to have each specific app override the constants?

更新 我花了很长时间决定其精湛的答案我已经提供了最适合我的需要(谢谢大家)最后,我选择了XML解决方案。我特别不喜欢它,因为它杂波了我的应用程序的资源,我也认真考虑使用该接口的解决方案,但XML解决方案并很好地工作。

Update I took a long time deciding on which of the superb answers I have been provided with best suited my needs (Thanks everyone) In the end I chose the xml solution. I don't particularly like it because it clutters up my apps resources and I did seriously consider using the interface solution but the xml solution does work nicely

推荐答案

选项#1 扩展您的AppConstants类每个项目

Option #1 Extend your AppConstants class in each project

更好的选择#2 使用XML资源定义常量

Better Option#2 Use XML resources to define the constants

<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="integer" name="app_id" format="integer">6</item>
</resources>

那么你可以通过

then you can retrieve them by

Context.getResources().getInteger(R.integer.app_id);

在XML文件中的每个项目只有你需要不同的值添加到您的资源

add the xml file to your resources in each project with only the values you need different