Метод gettext android studio

EditText

Компонент EditText — это текстовое поле для пользовательского ввода, которое используется, если необходимо редактирование текста. Следует заметить, что EditText является наследником TextView.

В Android Studio на панели инструментов текстовые поля можно найти в категории Texts под разными именами.

Для быстрой разработки текстовые поля снабдили различными свойствами и дали разные имена: Plain Text, Person Name, Password, Password (Numeric), E-mail, Phone, Postal Address, Multiline Text, Time, Date, Number, Number (Signed), NumberDecimal.

Plain Text

Plain Text — самый простой вариант текстового поля без наворотов. При добавлении в разметку его XML-представление будет следующим:

Person Name

При использовании элемента Person Name в XML добавляется атрибут inputType, который отвечает за вид клавиатуры (только буквы) при вводе текста.

Password и Password (Numeric)

При использовании Password в inputType используется значение textPassword. При вводе текста сначала показывается символ, который заменяется на звёздочку. Если используется элемент Password (Numeric), то у атрибута inputType используется значение numberPassword. В этом случае на клавиатуре будут только цифры вместо букв. Вот и вся разница.

E-mail

У элемента E-mail используется атрибут android:inputType=»textEmailAddress». В этом случае на клавиатуре появляется дополнительная клавиша с символом @, который обязательно используется в любом электронном адресе.

Phone

У элемента Phone используется атрибут android:inputType=»phone». Клавиатура похожа на клавиатуру из старого кнопочного сотового телефона с цифрами, а также с кнопками звёздочки и решётки.

Postal Address

Multiline Text

У Multiline Text используется атрибут android:inputType=»textMultiLine» позволяющий сделать текстовое поле многострочным. Дополнительно можете установить свойство Lines (атрибут android:lines), чтобы указать количество видимых строк на экране.

Time и Date

Атрибут android:inputType=»time» или android:inputType=»date». На клавиатуре цифры, точка, запятая, тире.

Number, Number (Signed), Number (Decimal)

Атрибут android:inputType=»number» или numberSigned или numberDecimal. На клавиатуре только цифры и некоторые другие символы.

Текст-подсказка

Веб-мастера знают о таком атрибуте HTML5 как placeholder, когда в текстовом поле выводится строчка-подсказка приглушенным (обычно серым цветом). Живой пример приведён ниже.

Подсказка видна, если текстовый элемент не содержит пользовательского текста. Как только пользователь начинает вводить текст, то подсказка исчезает. Соответственно, если удалить пользовательский текст, то подсказка появляется снова. Это очень удобное решение во многих случаях, когда на экране мало места для элементов.

В Android у многих элементов есть свойство Hint (атрибут hint), который работает аналогичным образом. Установите у данного свойства нужный текст и у вас появится текстовое поле с подсказкой.

Запускаем приложение и видим подсказку, которая исчезает при попытке ввести текст.

Вызов нужной клавиатуры

Не во всех случаях нужна стандартная клавиатура с буковками и цифрами. Если вы пишете калькулятор, то проще показать пользователю цифровую клавиатуру. А если нужно ввести электронный адрес, то удобнее показать клавиатуру, где уже есть символ @. Ну а если ваше приложение пишется для котов, то достаточно вывести только те буквы, из которых можно составить слова Мяу и Жрать давай (к сожалению, такой клавиатуры ещё нет, но Google работает в этом направлении).

У элемента EditText на этот случай есть атрибут inputType:

В данном случае с атрибутом inputType=»textCapWords&quot каждый первый символ каждого слова при вводе текста автоматически будет преобразовываться в прописную. Удобно, не так ли?

Значение textCapSentences делает прописным каждый первый символ предложения.

Если вам нужен режим CapsLock, то используйте значение textCapCharacters и все буквы сразу будут большими при наборе.

Для набора телефонного номера используйте phone, и тогда вам будут доступны только цифры, звёздочка (*), решётка (#).

Для ввода веб-адресов удобно использовать значение textUri. В этом случае у вас появится дополнительная кнопочка .com (при долгом нажатии на нее появятся альтернативные варианты .net, .org и др.).

Вот вам целый список доступных значений (иногда различия очень трудно различимы)

Интерфейс InputType

Кроме использования атрибута android:inputType мы можем добиться нужного поведения от текста при помощи интерфейса InputType.

Атрибут android:imeOptions — параметры для текущего метода ввода

У текстовых полей есть атрибут android:imeOptions, с помощью которого настраиваются параметры для текущего метода ввода. Например, когда EditText получает фокус и отображается виртуальная клавиатура, эта клавиатура содержит кнопку «Next» (Далее), если атрибут android:imeOptions содержит значение actionNext. Если пользователь касается этой кнопки, фокус перемещается к следующему компоненту, который принимает пользовательский ввод. Если компонент EditText получает фокус и на виртуальной клавиатуре появляется кнопка «Done» (Готово), значит использовался атрибут android:imeOptions со значением actionDone. Как только пользователь касается этой кнопки, система скрывает виртуальную клавиатуру.

Заблокировать текстовое поле

Для блокировки текстового поля присвойте значения false свойствам Focusable, Long clickable и Cursor visible.

Другие свойства

Методы

Основной метод класса EditTextgetText(), который возвращает текст, содержащийся в текстовом поле. Возвращаемое значение имеет специальный тип Editable, а не String.

Соответственно, для установки текста используется метод setText().

В Kotlin может возникнуть проблема, если программист захочет использовать конструкцию присвоения через свойство.

Большинство методов для работы с текстом унаследованы от базового класса TextView: setTypeface(null, Typeface), setTextSize(int textSize), SetTextColor(int Color).

Выделение текста

У EditText есть специальные методы для выделения текста:

  • selectAll() — выделяет весь текст;
  • setSelection(int start, int stop) — выделяет участок текста с позиции start до позиции stop;
  • setSelection(int index) — перемещает курсор на позицию index;

Предположим, нам нужно выделить популярное слово из трёх букв в большом слове (это слово «кот», а вы что подумали?).

Ещё есть метод setSelectAllOnFocus(), который позволяет выделить весь текст при получении фокуса.

Обработка нажатий клавиш

Для обработки нажатий клавиш необходимо зарегистрировать обработчик View.OnKeyListener, используя метод setOnKeyListener() элемента EditText. Например, для прослушивания события нажатия клавиши Enter во время ввода текста пользователем (или котом), используйте следующий код:

Пустой ли EditText

Чтобы проверить, пустой ли EditText, можно воспользоваться кодом:

Читайте также:  Удаленный рабочий стол rdp android

Также можно проверять длину текста, если она равно 0, значит текст пуст.

Превращаем EditText в TextView

Практического смысла тут нет, но для общего развития превратим текстовое поле в текстовую метку. Для этого нужно сделать компонент недоступным, убрать курсор, установить прозрачный фон и отключить слушатель нажатий клавиш.

Также можно установить эти свойства через XML, кроме последнего пункта.

Дополнительное чтение

Beware EditText on API 21 — разница между версиями 21 и 22

Источник

Get Value from the EditText and Set value to the TextView

Any android app has two parts in it – frontend and backend. Frontend refers to the visualization of the components i.e. how your app will look and appear to the other users. Backend part refers to the logic behind the functioning of your app.

Whenever we click on any button or submit any form, the backend code decides what action to perform next or what to do with the data received from user etc.

In our previous tutorials, we have seen how different types of layout are useful for for GUI designing which is the frontend part. Here in this tutorial, we are going to focus and code for the backend part.

In our example, we will take input from the user through EditText view and will display it in the TextView . Additionally, we will also get to see a buttonClickListener that is used to define the action to be performed when a button is clicked in the app.

Below is th design that we will be working on.

In the MainActivity.java file, we will define global variables as follows:

After setting the main layout using the setContentView() method in the onCreate() method, attach the global variables that we defined to the GUI views using findViewById() method as shown below.

As the name of the method suggests, findViewById() returns an instance for the view defined in layout XML. In other words, this method is used to get the view instance in Java, that you have made and used in layout XML. This is done by mentioning the id of the view that you have defined in XML. The view created in XML is used in Java to manipulate it dynamically.

Note: findViewById() method returns only View , but it does not tell which view is returned i.e. whether the view is Button, TextView, EditText, etc. Therefore, you need to typecast the view returned by this method.

Now, to enable button click event, we need to attach a click listener to our button instance. It is done by writing the following code:

Once you add this code, whenever th submit button is clicked, the method onClick will be called and the code inside it will be executed.

According to your requirements, we want to get the text that user will enter in the EditText and show it in the TextView whenever the submit button is clicked. Therefore, let’s place the following code inside onClick() method:

We have used getText() method to get the text entered in the EditText views. But getText() method returns an Editable instance and therefore we have typecasted it to convert it into String for further use. This can be done by using the toString() method.

Note: We defined editName and editPassword as global variables, hence they can be used in any method.

So now that we have user inputted name and password values, we can easily apply any logic on this dataset like performing authentication for login etc. For now, we are just going to display this information in a textView. For that, we will be using the setText() method with our TextView instance to display information in it. This is done using the following code:

Now, whenever the submit button is clicked, onClick() method of submitButton is called and the user input values are stored in the name and password variables using the getText() method on EditText instances. Then, using setText() method, the input values are displayed in the TextView.

Now, when you press the Reset button, the text in the TextView should be reset i.e cleared. For that, we will have to implement click listener on RESET button too. Following is the code to do so:

You just need to set text equal to «» (empty), for both the EditText as well as for TextView. Additionally, to get the typing cursor on the Name EditText field, we can use requestFocus() method with the editName instance.

Complete Code for MainActivity.java

You can download the whole project here

Add Validation if you want

You can also add validation to this like display a message if the user leaves the fields name and password empty and taps on the submit button.

In that case, all we have to do is check if name or password is empty, if found empty, display a message using a Toast saying, both the fields are required.

Источник

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.

Any of the following:

  • \’
  • Enclose the entire string in double quotes ( «This’ll work» , for example)
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 strings

If 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:

Kotlin

Styling with HTML markup

You can add styling to your strings with HTML markup. For example:

The following HTML elements are supported:

  • Bold: ,
  • Italic: , ,
  • 25% larger text:
  • 20% smaller text:
  • Setting font properties: . Examples of possible font families include monospace , serif , and sans_serif .
  • Setting a monospace font family:
  • Strikethrough: , ,
  • Underline:
  • Superscript:
  • Subscript:
  • Bullet points:
      ,
    • Line breaks:
    • Division:

    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:

      Store your styled text resource as an HTML-escaped string:

    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:

    Kotlin

    Because 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:

    Kotlin

    Styling with spannables

    A 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:

    Kotlin

    The 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.

    Kotlin

    Here’s an example of how to chain these methods together to apply various styles to individual words within a phrase:

    Kotlin

    The 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


    Applying a custom typeface to the word “text” in all languages

    Example — adding a custom typeface

    Load the string resource and find the annotations with the font key. Then create a custom span and replace the existing span.

    Kotlin

    If 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 parceling

    Because 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:

    Kotlin

    Retrieve the text from the Bundle as a SpannableString and then parse the annotations attached, as shown in the example above.

    Kotlin

    For 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.

    Источник

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