- getString вне контекста или действия
- Да, мы можем получить доступ к ресурсам, не используя `Context`
- Уникальный подход
- App.getRes().getString(R.string.some_id)
- GetString вне контекста или действия
- Да, мы можем получить доступ к ресурсам без использования `Context`
- Android: как получить строку из ресурсов по ее имени?
- 17 ответов
- Лучший подход
- Будет работать везде (также утилиты, модели).
- Проблема
- Android: Как получить строку из ресурсов, используя ее имя?
- 11 ответов:
- String resources
- String
- Kotlin
- String array
- Kotlin
- Quantity strings (plurals)
- Kotlin
- Format and style
- Handle special characters
- Formatting strings
- Kotlin
- Styling with HTML markup
- Kotlin
- Kotlin
- Styling with spannables
- Kotlin
- Kotlin
- Kotlin
- Styling with annotations
- Example — adding a custom typeface
- Kotlin
- Annotation spans and text parceling
- Kotlin
- Kotlin
getString вне контекста или действия
Я нашел R.string довольно удивительным то, что я не могу использовать жестко запрограммированные строки в своем коде, и я хотел бы продолжать использовать его в служебном классе, который работает с моделями в моем приложении для генерации вывода. Например, в этом случае я генерирую электронное письмо из модели вне действия.
Можно ли использовать getString снаружи Context или Activity ? Полагаю, я мог бы перейти к текущей деятельности, но это кажется ненужным. Пожалуйста, поправьте меня, если я ошибаюсь!
Изменить: Можем ли мы получить доступ к ресурсам без использования Context ?
Да, мы можем получить доступ к ресурсам, не используя `Context`
Ты можешь использовать:
. везде в вашем приложении, даже в объявлениях статических констант. К сожалению, он поддерживает только системные ресурсы .
Для локальных ресурсов используйте это решение . Это не тривиально, но работает.
К сожалению, единственный способ получить доступ к любому из строковых ресурсов — с помощью Context (то есть Activity или Service ). Что я обычно делал в этом случае, так это просто требовал, чтобы вызывающая сторона передавала контекст.
В MyApplication который распространяется Application :
В MyApplication х onCreate :
Теперь вы можете использовать это поле в любом месте вашего приложения.
Кстати, одной из причин ошибки символа не может быть то, что ваша IDE импортировала android.R; класс вместо твоего. Просто измените импорт android.R; чтобы импортировать your.namespace.R;
Итак, 2 основных вещи, чтобы сделать строку видимой в другом классе:
Уникальный подход
App.getRes().getString(R.string.some_id)
Это будет работать везде в приложении. ( Класс Util, диалог, фрагмент или любой класс в вашем приложении )
(1) Создайте или отредактируйте (если уже существует) свой Application класс.
(2) Добавьте поле имени к вашему manifest.xml тегу.
Теперь вы готовы идти. Используйте в App.getRes().getString(R.string.some_id) любом месте приложения.
Если у вас есть класс, который вы используете в действии, и вы хотите иметь доступ к ресурсам в этом классе, я рекомендую вам определить контекст как частную переменную в классе и инициализировать его в конструкторе:
Сделайте мгновение класса в своей деятельности:
Это должно дать вам доступ applicationContext из любого места, что позволит вам получить доступ к любому applicationContext месту, которое может его использовать; Toast , getString() , sharedPreferences И т.д.
Инициализируйте Singleton в своем Application подклассе:
Если я не ошибаюсь, это дает вам ApplicationContextSingleton.getInstance.getApplicationContext(); повод для приложенияContext повсюду, вызывайте его с помощью Вам не нужно очищать это в любой момент, так как когда приложение закрывается, это все равно идет с этим.
Не забудьте обновить AndroidManifest.xml чтобы использовать этот Application подкласс:
Пожалуйста, дайте мне знать, если вы видите здесь что-то не так, спасибо. 🙂
Лучший подход из ответа Хемрая:
Класс приложения
Декларация в манифесте
Класс констант
С помощью
Лучше использовать что-то подобное без контекста и активности :
Каким-то образом не понравились хакерские решения для хранения статических значений, поэтому мы получили немного более длинную, но чистую версию, которая также может быть протестирована.
Найдены 2 возможных способа сделать это
- Передайте context.resources в качестве параметра вашему классу, где вы хотите получить строковый ресурс. Довольно просто. Если передача в качестве параметра невозможна, используйте установщик.
- Используйте привязку данных (хотя требуется фрагмент / активность)
Прежде чем читать: эта версия использует Data binding
Иногда вам нужно изменить текст на основе поля в модели. Таким образом, вы бы также привязали данные к этой модели, и поскольку ваша деятельность / фрагмент знает о модели, вы можете очень легко получить значение и затем привязать данные к строке на основе этого.
Вы можете сделать это в Kotlin , создав класс, расширяющий Application, а затем использовать его контекст для вызова ресурсов в любом месте вашего кода.
Ваш класс приложения будет выглядеть так
Объявите свой класс приложения в AndroidManifest.xml (очень важно)
Например, для доступа к строковому файлу используйте следующий код
Вот что я сделал. В вашей MainActivity создайте статическую переменную для контекста, как показано ниже:
и в onCreate () инициализируйте mContext для этого;
Затем в файле, где вы хотите получить доступ к контексту, скажем,
Теперь вы можете получить строковый ресурс следующим образом,
Источник
GetString вне контекста или действия
Я нашел R.string довольно удивительным для хранения жестко заданных строк из моего кода, и я бы хотел использовать его в классе утилиты, который работает с моделями в моем приложении для генерации вывода. Например, в этом случае я генерирую электронное письмо от модели за пределами действия.
Можно ли использовать getString вне Context или Activity ? Полагаю, я мог бы пройти в текущей деятельности, но это кажется ненужным. Пожалуйста, поправьте меня, если я ошибаюсь!
Изменить. Можем ли мы получить доступ к ресурсам без использования Context ?
Да, мы можем получить доступ к ресурсам без использования `Context`
Вы можете использовать:
… везде в вашем приложении, даже в объявлениях статических констант. К сожалению, он поддерживает только системные ресурсы .
Для локальных ресурсов используйте это решение . Это не тривиально, но оно работает.
К сожалению, единственный способ доступа к любому из строковых ресурсов – это Context (т. Е. Activity или Service ). То, что я обычно делал в этом случае, – это просто потребовать, чтобы вызывающий вызывал в контексте.
В MyApplication, который расширяет Application :
В MyApplication’s onCreate:
Та-да . Теперь вы можете использовать это поле из любого места в своем приложении.
BTW, одна из причин ошибки, которую не обнаружил символ, может заключаться в том, что ваша IDE импортировала android.R; Вместо вашего. Просто измените import android.R; Для импорта your.namespace.R;
Итак, две основные вещи, чтобы получить строку, видимую в разных классах:
Если у вас есть класс, который вы используете в действии, и вы хотите получить доступ к ressource в этом классе, я рекомендую вам определить контекст как приватную переменную в классе и инициализировать его в конструкторе:
Создание момента занятия в вашей деятельности:
Это должно обеспечить вам доступ к applicationContext из любого места, позволяя вам получать applicationContext любом месте, где можно его использовать; Toast , getString() , sharedPreferences и т. Д.
Инициализируйте Singleton в подклассе Application :
Если я не ошибаюсь, это дает вам доступ к applicationContext везде, назовите его с помощью ApplicationContextSingleton.getInstance.getApplicationContext(); Вы не должны очищать это в любой момент, так как когда приложение закрывается, все равно это происходит.
Не забудьте обновить AndroidManifest.xml для использования этого подкласса Application :
Пожалуйста, дайте мне знать, если вы видите что-то не так, спасибо. 🙂
Источник
Android: как получить строку из ресурсов по ее имени?
Я хотел бы иметь 2 языка для пользовательского интерфейса и отдельные строковые значения для них в моем файле ресурсов res\values\strings.xml :
Теперь мне нужно динамически получать эти значения в моем приложении:
Моя проблема в том, что i = 0 .
Почему в моем случае не работает?
17 ответов
Ссылка, на которую вы ссылаетесь, похоже, работает со строками, созданными во время выполнения. Строки из strings.xml не создаются во время выполнения. Вы можете получить их через
getResources() — это метод класса Context . Если вы находитесь внутри Activity или Service (которые расширяют контекст), вы можете использовать его, как в этом фрагменте.
Также обратите внимание, что обо всех языковых зависимостях может позаботиться платформа Android . Просто создайте разные папки для каждого языка. Если английский является вашим языком по умолчанию, просто поместите английские строки в res/values/strings.xml . Затем создайте новую папку values-ru и поместите русские строки с одинаковыми именами в res/values-ru/strings.xml . С этого момента Android выбирает правильный вариант в зависимости от языкового стандарта устройства, когда вы вызываете getString() или когда ссылаетесь на строки в XML через @string/mystring . Те из res/values/strings.xml являются резервными, если у вас нет папки, охватывающей локаль пользователя, она будет использоваться в качестве значений по умолчанию.
См. Локализацию и Предоставление ресурсов для получения дополнительной информации.
Используйте эту строку непосредственно в своем java-файле. Будьте проще.
В целях безопасности вы должны добавить: mContext.getResources (). GetString (R.string.your_string);
MContext может быть: контекстом в onAttach () фрагмента или этим элементом действия.
Если вы не хотите помещать его в активность или фрагмент, тогда:
Если вы хотите получить его из класса вне активности или фрагмента, где у вас нет контекста активности, используйте контекст приложения:
Вы можете попробовать это в Activity:
В других ситуациях, таких как фрагменты, . используйте
Строка myString = getString (R.string.mystring);
Существует также набор предопределенных строк Android , таких как «ОК», «Отмена» и многих других, поэтому вам не нужно объявлять все. Они доступны просто:
(В данном случае строка «ОК»). Кстати, есть и другие ресурсы Android, такие как, например, изображения значков и т. Д.
getResources() работает, только когда вы находитесь в классе Activity или Fragment .
- чтобы получить доступ к строковому ресурсу везде,
Если вы используете Kotlin , вы можете определить функцию расширения следующим образом:
А потом просто используйте это. Например, в приложении Puzzles я устанавливаю заголовок Activity в соответствии с именем файла изображения:
В этом примере я читаю строковые ресурсы на основе динамических имен.
Если у вас нет ссылки на Activity, вы можете использовать свой контекст следующим образом:
Лучший подход
App.getRes().getString(R.string.some_id)
Будет работать везде (также утилиты, модели).
Я прочитал все ответы, все ответы могут помочь вам в работе.
- Вы можете использовать getString(R.string.some_string_id) как в Activity , так и в Fragment .
- Вы можете использовать Context.getString(R.string.some_string_id) там, где у вас нет прямого доступа к методу getString() . Как Dialog .
Проблема
Когда у вас нет доступа к Context , например к методу в вашем классе Util .
Предположим, что метод ниже без контекста.
Теперь вы передадите Context в качестве параметра в этом методе и используйте getString().
Что я делаю
Что? Его очень просто использовать в любом месте вашего приложения!
Итак, вот решение , с помощью которого вы можете получить доступ к ресурсам из любого места, например Util class .
Добавьте поле имени в свой тег manifest.xml .
Теперь можно идти. Используйте App.getAppResources().getString(R.string.some_id) в любом месте приложения.
Простой способ получить строку ресурса из строки в TextView. Здесь resourceName — это имя ресурса.
Более простой способ — использовать функцию getString() внутри действия.
Я думаю, что эта функция добавлена в последнюю версию Android, любой, кто знает историю, может это прокомментировать.
Я бы добавил кое-что к решению leonvian, поэтому, если по какой-то причине строка не будет найдена среди ресурсов (возвращаемое значение 0, это недопустимый код ресурса), функция может что-то вернуть:
Источник
Android: Как получить строку из ресурсов, используя ее имя?
Я хотел бы иметь 2 языка для пользовательского интерфейса и отдельные строковые значения для них в моем файле ресурсов resvaluesstrings.xml :
теперь мне нужно получить эти значения динамически в мое приложение:
моя проблема в том, что i = 0 .
Почему это не работает в моем случае?
11 ответов:
ссылка, на которую вы ссылаетесь, похоже, работает со строками, созданными во время выполнения. Строки из строк.xml не создаются во время выполнения. Вы можете получить их через
getResources() метод Context класса. Если вы находитесь внутри Activity или Service (которые расширяют контекст) вы можете использовать его как в этом фрагменте.
и обратите внимание, что вся языковая зависимость может быть решена с помощью Android framework. Просто создайте различные папки для каждого языка. Если английский язык является вашим языком по умолчанию, просто поместите английские строки в res/values/strings.xml . Затем создайте новую папку values-ru и поставить русские строки с одинаковыми именами в res/values-ru/strings.xml . С этого момента android выбирает правильный в зависимости от локали устройства для вас, либо при вызове getString() или при ссылке на строки в XML через @string/mystring . Те, что из res/values/strings.xml являются резервными, если у вас нет папки, охватывающей пользователей язык, это будет использоваться в качестве значения по умолчанию.
посмотреть локализация и Выделение Ресурсов для получения дополнительной информации.
У меня та же проблема. Но этот код ниже работает для меня: Проверьте правильность имени пакета. Вы должны обратиться к корневому пакету вашего приложения для Android.
Источник
String resources
A string resource provides text strings for your application with optional text styling and formatting. There are three types of resources that can provide your application with strings:
String XML resource that provides a single string. String Array XML resource that provides an array of strings. Quantity Strings (Plurals) XML resource that carries different strings for pluralization.
All strings are capable of applying some styling markup and formatting arguments. For information about styling and formatting strings, see the section about Formatting and Styling.
String
A single string that can be referenced from the application or from other resource files (such as an XML layout).
Note: A string is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). So, you can combine string resources with other simple resources in the one XML file, under one element.
file location: res/values/filename.xml
The filename is arbitrary. The element’s name is used as the resource ID. compiled resource datatype: Resource pointer to a String . resource reference: In Java: R.string.string_name
In XML: @string/string_name syntax: elements: Required. This must be the root node.
A string, which can include styling tags. Beware that you must escape apostrophes and quotation marks. For more information about how to properly style and format your strings see Formatting and Styling, below.
name String. A name for the string. This name is used as the resource ID. example: XML file saved at res/values/strings.xml :
This layout XML applies a string to a View:
This application code retrieves a string:
Kotlin
You can use either getString(int) or getText(int) to retrieve a string. getText(int) retains any rich text styling applied to the string.
String array
An array of strings that can be referenced from the application.
Note: A string array is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). As such, you can combine string array resources with other simple resources in the one XML file, under one element.
file location: res/values/filename.xml
The filename is arbitrary. The element’s name is used as the resource ID. compiled resource datatype: Resource pointer to an array of String s. resource reference: In Java: R.array.string_array_name
In XML: @[package:]array/string_array_name syntax: elements: Required. This must be the root node.
Defines an array of strings. Contains one or more elements.
name String. A name for the array. This name is used as the resource ID to reference the array. A string, which can include styling tags. The value can be a reference to another string resource. Must be a child of a element. Beware that you must escape apostrophes and quotation marks. See Formatting and Styling, below, for information about to properly style and format your strings.
example: XML file saved at res/values/strings.xml :
This application code retrieves a string array:
Kotlin
Quantity strings (plurals)
Different languages have different rules for grammatical agreement with quantity. In English, for example, the quantity 1 is a special case. We write «1 book», but for any other quantity we’d write «n books». This distinction between singular and plural is very common, but other languages make finer distinctions. The full set supported by Android is zero , one , two , few , many , and other .
The rules for deciding which case to use for a given language and quantity can be very complex, so Android provides you with methods such as getQuantityString() to select the appropriate resource for you.
Although historically called «quantity strings» (and still called that in API), quantity strings should only be used for plurals. It would be a mistake to use quantity strings to implement something like Gmail’s «Inbox» versus «Inbox (12)» when there are unread messages, for example. It might seem convenient to use quantity strings instead of an if statement, but it’s important to note that some languages (such as Chinese) don’t make these grammatical distinctions at all, so you’ll always get the other string.
The selection of which string to use is made solely based on grammatical necessity. In English, a string for zero is ignored even if the quantity is 0, because 0 isn’t grammatically different from 2, or any other number except 1 («zero books», «one book», «two books», and so on). Conversely, in Korean only the other string is ever used.
Don’t be misled either by the fact that, say, two sounds like it could only apply to the quantity 2: a language may require that 2, 12, 102 (and so on) are all treated like one another but differently to other quantities. Rely on your translator to know what distinctions their language actually insists upon.
It’s often possible to avoid quantity strings by using quantity-neutral formulations such as «Books: 1». This makes your life and your translators’ lives easier, if it’s an acceptable style for your application.
Note: A plurals collection is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). As such, you can combine plurals resources with other simple resources in the one XML file, under one element.
file location: res/values/filename.xml
The filename is arbitrary. The
element’s name is used as the resource ID. resource reference: In Java: R.plurals.plural_name syntax: elements: Required. This must be the root node.
A collection of strings, of which, one string is provided depending on the amount of something. Contains one or more elements.
name String. A name for the pair of strings. This name is used as the resource ID. A plural or singular string. The value can be a reference to another string resource. Must be a child of a
element. Beware that you must escape apostrophes and quotation marks. See Formatting and Styling, below, for information about to properly style and format your strings.
quantity Keyword. A value indicating when this string should be used. Valid values, with non-exhaustive examples in parentheses:
Value | Description |
---|---|
zero | When the language requires special treatment of the number 0 (as in Arabic). |
one | When the language requires special treatment of numbers like one (as with the number 1 in English and most other languages; in Russian, any number ending in 1 but not ending in 11 is in this class). |
two | When the language requires special treatment of numbers like two (as with 2 in Welsh, or 102 in Slovenian). |
few | When the language requires special treatment of «small» numbers (as with 2, 3, and 4 in Czech; or numbers ending 2, 3, or 4 but not 12, 13, or 14 in Polish). |
many | When the language requires special treatment of «large» numbers (as with numbers ending 11-99 in Maltese). |
other | When the language does not require special treatment of the given quantity (as with all numbers in Chinese, or 42 in English). |
example: XML file saved at res/values/strings.xml :
XML file saved at res/values-pl/strings.xml :
Kotlin
When using the getQuantityString() method, you need to pass the count twice if your string includes string formatting with a number. For example, for the string %d songs found , the first count parameter selects the appropriate plural string and the second count parameter is inserted into the %d placeholder. If your plural strings do not include string formatting, you don’t need to pass the third parameter to getQuantityString .
Format and style
Here are a few important things you should know about how to properly format and style your string resources.
Handle special characters
When a string contains characters that have special usage in XML, you must escape the characters according to the standard XML/HTML escaping rules. If you need to escape a character that has special meaning in Android you should use a preceding backslash.
By default Android will collapse sequences of whitespace characters into a single space. You can avoid this by enclosing the relevant part of your string in double quotes. In this case all whitespace characters (including new lines) will get preserved within the quoted region. Double quotes will allow you to use regular single unescaped quotes as well.
Character | Escaped form(s) |
---|---|
@ | \@ |
? | \? |
New line | \n |
Tab | \t |
U+XXXX Unicode character | \uXXXX |
Single quote ( ‘ ) | |
Double quote ( » ) | \» Note that surrounding the string with single quotes does not work. Whitespace collapsing and Android escaping happens after your resource file gets parsed as XML. This means that (space, punctuation space, Unicode Em space) all collapse to a single space ( » » ), because they are all Unicode spaces after the file is parsed as an XML. To preserve those spaces as they are, you can either quote them ( » » ) or use Android escaping ( \u0032 \u8200 \u8195 ). Note: From XML parser’s perspective, there is no difference between «Test this» and «Test this» whatsoever. Both forms will not show any quotes but trigger Android whitespace-preserving quoting (that will have no practical effect in this case). Formatting stringsIf you need to format your strings, then you can do so by putting your format arguments in the string resource, as demonstrated by the following example resource. In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. Then, format the string by calling getString(int, Object. ) . For example: KotlinStyling with HTML markupYou can add styling to your strings with HTML markup. For example: The following HTML elements are supported:
If you aren’t applying formatting, you can set TextView text directly by calling setText(java.lang.CharSequence) . In some cases, however, you may want to create a styled text resource that is also used as a format string. Normally, this doesn’t work because the format(String, Object. ) and getString(int, Object. ) methods strip all the style information from the string. The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String) , after the formatting takes place. For example:
In this formatted string, a element is added. Notice that the opening bracket is HTML-escaped, using the notation. Then format the string as usual, but also call fromHtml(String) to convert the HTML text into styled text: KotlinBecause the fromHtml(String) method formats all HTML entities, be sure to escape any possible HTML characters in the strings you use with the formatted text, using htmlEncode(String) . For instance, if you are formatting a string that contains characters such as » fromHtml(String) , the characters come out the way they were originally written. For example: KotlinStyling with spannablesA Spannable is a text object that you can style with typeface properties such as color and font weight. You use SpannableStringBuilder to build your text and then apply styles defined in the android.text.style package to the text. You can use the following helper methods to set up much of the work of creating spannable text: KotlinThe following bold , italic , and color methods wrap the helper methods above and demonstrate specific examples of applying styles defined in the android.text.style package. You can create similar methods to do other types of text styling. KotlinHere’s an example of how to chain these methods together to apply various styles to individual words within a phrase: KotlinThe core-ktx Kotlin module also contains extension functions that make working with spans even easier. You can check out the android.text package documentation on GitHub to learn more. For more information on working with spans, see the following links: Styling with annotations
Example — adding a custom typefaceLoad the string resource and find the annotations with the font key. Then create a custom span and replace the existing span. KotlinIf you’re using the same text multiple times, you should construct the SpannableString object once and reuse it as needed to avoid potential performance and memory issues. For more examples of annotation usage, see Styling internationalized text in Android Annotation spans and text parcelingBecause Annotation spans are also ParcelableSpans , the key-value pairs are parceled and unparceled. As long as the receiver of the parcel knows how to interpret the annotations, you can use Annotation spans to apply custom styling to the parceled text. To keep your custom styling when you pass the text to an Intent Bundle, you first need to add Annotation spans to your text. You can do this in the XML resources via the tag, as shown in the example above, or in code by creating a new Annotation and setting it as a span, as shown below: KotlinRetrieve the text from the Bundle as a SpannableString and then parse the annotations attached, as shown in the example above. KotlinFor more information on text styling, see the following links: Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates. Источник |