Android text from string

Как получить текст из ресурсов (string.xml)

У меня есть некий код (Android 2.3.3).

Метод Pattern.compile(String string) , требует параметр в виде строк, но из string.xml я получаю int . Т.е. я получаю итендификаторы из R.java , но мне нужны сразу строки.

Cами ресурсы из string.xml

Один вариант приведения в качестве строки:

Не могу использовать данные варианты, т.к. методов getString(. ), getResources() Eclipse не видит.

Как мне брать из string.xml сразу строку, а не ее id ? Если можно с примером.

2 ответа 2

Методы getResources() или getString() вызываются из Context , так как context имеет доступ к ресурсам программы.

А строку получить нельзя из string.xml .

Как вариант костыля, можно написать enum :), но так не стоит делать либо используй public static final string в классе в котором пользуешься Pattern

Используемые вами методы getResources() и getString() — методы контекста (класса Context ) и чтобы получить результат, вам нужно сначала получить в свой класс контекст любым доступным способом, от передачи в свой класс через конструктор оттуда, где контекст есть (например, при вызове своего класса из активити, которая наследуется от класса Context и содержит его) до получения контекста из Application — этот класс доступен всегда в приложении и содержит контекст.

Получив экземпляр контекста вы можете использовать его методы в своем классе:

Напрямую контекст можно получить из классов Application , Activity (и ее наследников), Service , Fragment (и его наследников, через метод getActivity() ) и др. Всего 45 классов (раздел Known Indirect Subclasses)

Всё ещё ищете ответ? Посмотрите другие вопросы с метками android resources или задайте свой вопрос.

Связанные

Похожие

Подписаться на ленту

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.12.3.40888

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Источник

Set TextView text from html-formatted string resource in XML

I have some fixed strings inside my strings.xml , something like:

and in my layout I’ve got a TextView which I’d like to fill with the html-formatted string.

if I do this, the content of formattedtext is just the content of somestring stripped of any html tags and thus unformatted.

I know that it is possible to set the formatted text programmatically with

because I use this in other parts of my program where it is working as expected.

Читайте также:  Баду премиум навсегда андроид

To call this function I need an Activity , but at the moment my layout is just a simple more or less static view in plain XML and I’d prefer to leave it that way, to save me from the overhead of creating an Activity just to set some text.

Am I overlooking something obvious? Is it not possible at all? Any help or workarounds welcome!

Edit: Just tried some things and it seems that HTML formatting in xml has some restraints:

tags must be written lowercase

some tags which are mentioned here do not work, e.g.
(it’s possible to use \n instead)

7 Answers 7

Just in case anybody finds this, there’s a nicer alternative that’s not documented (I tripped over it after searching for hours, and finally found it in the bug list for the Android SDK itself). You CAN include raw HTML in strings.xml, as long as you wrap it in

Edge Cases:

  • Characters like apostrophe (‘), double-quote («), and ampersand (&) only need to be escaped if you want them to appear in the rendered text AS themselves, but they COULD be plausibly interpreted as HTML.
    • ‘ and » can be represented as \’ and \» , or ‘ and » .
    • and >always need to be escaped as and > if you literally want them to render as ‘ ‘ in the text.
    • Ampersand (&) is a little more complicated.
      • Ampersand followed by whitespace renders as ampersand.
      • Ampersand followed by one or more characters that don’t form a valid HTML entity code render as Ampersand followed by those characters. So. &qqq; renders as &qqq; , but renders as .

Then, in your code:

IMHO, this is several orders of magnitude nicer to work with 🙂

August 2021 update: My original answer used Html.fromHtml(String), which was deprecated in API 24. The alternative fromHtml(String,int) form is suggested as its replacement.

FROM_HTML_MODE_LEGACY is likely to work. but one of the other flags might be a better choice for what you want to do.

On a final note, if you’d prefer to render Android Spanned text suitable for use in a TextView using Markdown syntax instead of HTML, there are now multiple thirdparty libraries to make it easy including https://noties.io/Markwon.

As the top answer here is suggesting something wrong (or at least too complicated), I feel this should be updated, although the question is quite old:

When using String resources in Android, you just have to call getString(. ) from Java code or use android:text=»@string/. » in your layout XML.

Even if you want to use HTML markup in your Strings, you don’t have to change a lot:

The only characters that you need to escape in your String resources are:

  • double quotation mark: » becomes \»
  • single quotation mark: ‘ becomes \’
  • ampersand: & becomes & or &
Читайте также:  Как заставить андроид летать

That means you can add your HTML markup without escaping the tags:

However, to be sure, you should only use , and as they are listed in the documentation.

If you want to use your HTML strings from XML, just keep on using android:text=»@string/. » , it will work fine.

The only difference is that, if you want to use your HTML strings from Java code, you have to use getText(. ) instead of getString(. ) now, as the former keeps the style and the latter will just strip it off.

It’s as easy as that. No CDATA, no Html.fromHtml(. ) .

You will only need Html.fromHtml(. ) if you did encode your special characters in HTML markup. Use it with getString(. ) then. This can be necessary if you want to pass the String to String.format(. ) .

This is all described in the docs as well.

Edit:

There is no difference between getText(. ) with unescaped HTML (as I’ve proposed) or CDATA sections and Html.fromHtml(. ) .

See the following graphic for a comparison:

Источник

how to read value from string.xml in android?

I have written the line:

to get string value, but instead of returning string, it is giving me id of type integer. How can I get its string value? I mentioned the string value in the string.xml file.

18 Answers 18

UPDATE

You can use either getString(int) or getText(int) to retrieve a string. getText(int) will retain any rich text styling applied to the string.

If not in activity but have access to context:

By the way, it is also possible to create string arrays in the strings.xml like so:

And then from your Activity you can get the reference like so:

Only for future references.

You can use either getString(int) or getText(int) to retrieve a string. getText(int) will >retain any rich text styling applied to the string.

In fragments, you can use

If you want to add the string value to a button for example, simple use

The defined text in strings.xml looks like this:

You must reference Context name before using getResources() in Android.

You can use this code:

Basically, you need to pass the resource id as a parameter to the getText() method.

If you are in an activity you can use

If you are not in an Activity use this :

Details

  • Android Studio 3.1.4
  • Kotlin version: 1.2.60
  • single line use
  • minimum code
  • use suggestions from the compiler

Step 1. Application()

Get link to the context of you application

Step 2. Add int extension

Usage

Results

while u write R . you are referring to the R.java class created by eclipse, use getResources().getString() and pass the id of the resource from which you are trying to read inside the getString() method.

Example : String[] yourStringArray = getResources().getStringArray(R.array.Your_array);

You can read directly the value defined into strings.xml:

and set into a variable:

but we can define the string into the view:

Читайте также:  Провод андроид микро usb

I hope this code is beneficial

Update

  • You can use getString(R.string.some_string_id) in both Activity or Fragment .
  • You can use Context.getString(R.string.some_string_id) where you don’t have direct access to getString() method. Like Dialog .

Problem is where you don’t have Context access, like a method in your Util class.

Assume below method without Context.

Now you will pass Context as a parameter in this method and use getString().

What i do is

What? It is very simple to use anywhere in your app!

So here is a Bonus unique solution by which you can access resources from anywhere like Util class .

Источник

Android string.xml — несколько вещей, которые стоит помнить

Доброго времени суток! Представляю вашему вниманию вольный перевод статьи от GDE (Google developer expert) Dmytro Danylyk. Собственно, вот оригинал. Статья описывает правильные подходы для работы со strings.xml и особенно полезно это будет разработчикам, которые разрабатывают мультиязыковые приложения. Прошу под кат.

Эта статья о такой тривиальной вещи android как string.xml.

Не используйте повторно

Не используйте повторно строки для разных экранов

Давайте представим, что у вас есть loading dialog на Sign In либо Sign Up экране. Так как оба экрана имеют loading dialog, вы решаете использовать те же строки — R.string.loading.

Позже, если вы решите использовать различные, вам нужно будет создать 2 разные строки и модифицировать их, непосредственно, в .java классах. Если вы используете разные строки с начала — вам бы пришлось модифицировать лишь strings.xml файл.

Вы никогда не будете заранее знать поддержку и перевод какого языка вам предстоит добавить. Всё дело в контексте: в одном языке вы можете использовать тоже слово в одном контексте, но в другом — это слово по смыслу не будет подходить.

Обратите внимание, что в данном случае английская версия strings.xml использует тоже самое слово — “Yes” для обоих случаев R.string.download_file_yes и R.string.terms_of_use_yes strings.
Но украинский вариант strings.xml использует 2 разных слова — “Гаразд” для R.string.download_file_yes и “Так” для R.string.terms_of_use_yes.

Разделяйте

Разделяйте строки, которые относятся к одному экрану с помощью префиксов и комментариев

  1. Добавляйте префикс в виде имени экрана к каждой строке для более простого понимания к какому экрану относится данный ресурс.
  2. Чистый string.xml файл поможет достаточно легко поддерживать и переводить различные языки — экран за экраном.

Создание различных strings.xml для каждого экрана

Если вы хотите, вы можете создать string.xml файл для каждого экрана — settings-strings.xml, profile-strings.xml. Но обычно приложение имеет около 10-20 экранов, соответственно, нужно иметь 10-20 string.xml файлов в каждой языковой папке. Я думаю, что это будет сопряжено с беспорядком.

Форматирование

Используйте Resources#getString(int id, Object… formatArgs) для форматирования строк

Никогда не делайте конкатенацию через + оператор, поскольку в других языках порядок слов может варьироваться.

Множественное число

Используйте Resources#getQuantityString(int id, int quantity) для количественных строк

Не решайте проблемы с множественным числом в java коде, поскольку разные языки имеют разные правила для согласования множественного числа

Подстветка слов

Используйте html text для подсветки статический слов

Источник

Оцените статью