简体   繁体   English

如何在接口中使用 getResources.getString(R.string)?

[英]How to use getResources.getString(R.string) in an Interface?

I have an interface that has a static key.我有一个带有静态密钥的界面。 And I wanted to retrieve this key from a string file, but if I just put R.string.key, it shows incompatible types, because it retrieves the integer value, and if I put R.string.key + "", it becomes a string but retrieves the String file id, it would be best to use getResources.getString (R.string.key), but there is no way to use the getResources.getString method in the Interface.我想从字符串文件中检索这个键,但如果我只放 R.string.key,它显示不兼容的类型,因为它检索整数值,如果我放 R.string.key + "",它变成一个字符串但是检索String文件id,最好使用getResources.getString(R.string.key),但是没有办法使用接口中的getResources.getString方法。

Working:在职的:

public interface NotificacaoService {
    @Headers({"34853485734",
            "Content-Type:application/json"}) @POST("send")
    Call<NotificacaoDados> salvarNotificacao(@Body NotificacaoDados notificacaoDados);
}

I want to leave it like this:我想像这样离开它:

public interface NotificacaoService {
    @Headers({getResources.getString(R.string.key),
            "Content-Type:application/json"}) @POST("send")
    Call<NotificacaoDados> salvarNotificacao(@Body NotificacaoDados notificacaoDados);
}

Sorry, what you want is not possible.对不起,你想要的不可能。 Annotation parameters need to be constants.注释参数需要是常量。

One solution is to switch from string resources to BuildConfig .一种解决方案是从字符串资源切换到BuildConfig Use buildConfigField in your Gradle script to define your key ( buildConfigField "String", "API_KEY", "\\"34853485734\\""). Then, you can reference that generated constant in your interface (eg,在您的 Gradle 脚本中使用buildConfigField来定义您的密钥( buildConfigField "String", "API_KEY", "\\"34853485734\\""). Then, you can reference that generated constant in your interface (eg, buildConfigField "String", "API_KEY", "\\"34853485734\\""). Then, you can reference that generated constant in your interface (eg, BuildConfig.API_KEY`). buildConfigField "String", "API_KEY", "\\"34853485734\\""). Then, you can reference that generated constant in your interface (eg, BuildConfig.API_KEY`)。

Alternatively — if this interface is for Retrofit — you could add your headers via an OkHttp interceptor, instead of via a @Headers annotation.或者——如果这个接口是用于改造的——你可以通过 OkHttp 拦截器添加你的头文件,而不是通过@Headers注释。

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

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