0

I'm developing an Android library.

This library has a utility class which contains static functions which include strings in them (mostly for detailed descriptions of various errors).

I want to localize these strings. Therefore, in the library, I've put these strings inside res/values/strings.xml.

In order to use these strings in my library code, I need to call getString() but this method requires a Context. The context MUST be the library context, since the strings are only defined in the library resources.

My research so far

I've searched for similar questions about using string resources inside static functions, but the answers given won't work in my case. The 2 popular answers were:

  1. Pass a context as an argument to the static functions - I think this won't work for me because the code using the utility class is the app using the library (not the library itself). This means the only possible context the caller could pass would be the app's context - but I need the library's context.

  2. Retrieve a context statically by accessing the Application object (usually via a singleton) and calling getApplicationContext() - I think this won't work for the same reason, the context will be the app's context and not the library's.

Any ideas?

I don't think I'm attempting anything peculiar. Developing a library for sharing and code reuse is perfectly normal. Having static utility functions in this library is perfectly normal. The usage of strings in these functions to describe error conditions is perfectly normal. And to want to localize these strings is normal. Why is this so difficult?!

4

1 回答 1

2

图书馆资源被吸收到使用它们的项目中——所以应用程序的上下文应该没问题。你试过这样做吗?

当我在 Library 项目中定义资源时,我会在我的 ID 前面加上 Library 名称,这样就不太可能发生冲突:R.string.mylib_astring.

此外,如果您通过R在您的应用程序中引用资源,它们将位于库的包中,而不是应用程序的包中。例如com.example.mylib.R,而不是com.example.myapp.R

于 2013-04-30T16:39:48.800 回答