Select all android text

Creating custom Text Selection actions with ACTION_PROCESS_TEXT

Android 6.0 Marshmallow introduced a new floating text selection toolbar, which brings the standard text selection actions, like cut, copy, and paste, closer to the text you’ve selected. Even better though is the new ACTION_PROCESS_TEXT which makes it possible for any app to add custom actions to that text selection toolbar.

Apps like Wikipedia and Google Translate are already taking advantage of it to instantly lookup or translate selected text.

You may have already seen documentation and a blog post about ensuring the text selection toolbar and options appear in your app (in short: using a standard TextView/ EditText and they’ll work out of the box, but note your EditText would need to have an android:id set and you need to call getDelegate() . setHandleNativeActionModesEnabled(false) if you are using AppCompatActivity and want to use the native floating text selection toolbar on API 23+ devices).

But finding information on implementing ACTION_PROCESS_TEXT and adding your own actions? That’s what this post will cover.

Cross app communication -> Intent Filters

As you might expect when building functionality that crosses app boundaries, your Android Manifest and the intent filters attached to each component serve as a public API that other apps can query.

ACTION_PROCESS_TEXT is no different. You’ll add an intent filter to an Activity in your manifest:

And, if you wanted multiple actions (you overachiever, you!), you’ll need separate activities for each. As of Android 6.0.1, you’ll want to avoid adding android:exported=”false” — your action will still appear in other apps, but they’ll get a SecurityException immediately upon clicking it (the feature request to implement filtering in ACTION_PROCESS_TEXT to match the behavior of the system chooser has been marked FutureRelease and fixed internally).

Note that the android:label of your Activity will show up as the action in the text selection toolbar so ensure it is short, an action verb, and recognizable as something iconic with your app. For example, Google Translate uses ‘Translate’ as it is a less common action (how many people have multiple translation apps installed?), while Wikipedia uses ‘Search Wikipedia’ as searching may be a much more common action for many apps.

Getting the selected text

Once you get your intent filter set up, other apps will already be able to start your activity by selecting text and choosing your action from the text selection toolbar. But that doesn’t add any value unless you actually look at the text that was selected.

That’s where EXTRA_PROCESS_TEXT comes in: it is a CharSequence included in the Intent that represents what text was selected. Don’t be deceived — even though you are using a text/plain intent filter, you’ll get the full CharSequence with any Spannables included, so don’t be surprised if you notice some styling if you use the CharSequence directly in your app (you can always call toString() to remove all formatting).

Therefore your onCreate() method may look something like:

With one caveat if you are using android:launchMode=”singleTop”, then you’ll also want to process text in onNewIntent() as well — a common practice is to have both onCreate() and onNewIntent() call a single handleIntent() method you create.

And that’s about all you’d need if you are using ACTION_PROCESS_TEXT as an entryway into your app: what you do with it after that point is up to you.

Returning a result

There’s one other extra included in the ACTION_PROCESS_TEXT Intent though: EXTRA_PROCESS_TEXT_READONLY. This boolean extra denotes whether the selected text you just received can be edited by the user (such as would be the case in an EditText).

Читайте также:  Тема для андроида механизм

You’d retrieve the extra with code such as

You can use this as a hint to offer the ability to return altered text to the sending app, replacing the selected text. This works as your Activity was actually started with startActivityForResult() — you’ll be able to return a result by calling setResult() at any time prior to your Activity finishing:

You could imagine a button to ‘Replace’ would call setResult() followed by finish() to return back to the calling Activity.

Common questions

Before you start writing responses, here’s some common questions about ACTION_PROCESS_TEXT:

Q: Can I trigger a Service with ACTION_PROCESS_TEXT?

A: Not directly — the system only looks for Activities that contain the correct intent filter. That doesn’t mean you can’t have your Activity launch a Service using a theme of Theme.Translucent.NoTitleBar or even Theme.NoDisplay (as long as you immediately finish the Activity), but make sure you have some user visible hint that their action was received — a notification starting, a Toast, etc.

Q: Can I trigger it only for certain types of text?

A: Nope. Your option will appear every time anyone selects text. Of course, chances are users won’t select an option to ‘Translate’ unless they want to translate, etc., but I’d be careful to code defensively as you cannot be sure what type of text context you’ll receive.

Q: So should every app implement ACTION_PROCESS_TEXT? Wouldn’t that be madness?

A: Yes, that would be madness and no, not every app should implement ACTION_PROCESS_TEXT. Make sure any actions you implement are universal and truly useful to users who have your app installed.

Learn more

Besides the aforementioned Wikipedia and Google Translate which already contain good, real world examples, you can also check out the ApiDemos app installed on Marshmallow emulators or look at the code directly.

Join the discussion on the Google+ post and follow the Android Development Patterns Collection for more!

Источник

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, можно воспользоваться кодом:

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

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

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

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

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

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

Источник

Creating custom Text Selection actions with ACTION_PROCESS_TEXT

Android 6.0 Marshmallow introduced a new floating text selection toolbar, which brings the standard text selection actions, like cut, copy, and paste, closer to the text you’ve selected. Even better though is the new ACTION_PROCESS_TEXT which makes it possible for any app to add custom actions to that text selection toolbar.

Apps like Wikipedia and Google Translate are already taking advantage of it to instantly lookup or translate selected text.

You may have already seen documentation and a blog post about ensuring the text selection toolbar and options appear in your app (in short: using a standard TextView/ EditText and they’ll work out of the box, but note your EditText would need to have an android:id set and you need to call getDelegate() . setHandleNativeActionModesEnabled(false) if you are using AppCompatActivity and want to use the native floating text selection toolbar on API 23+ devices).

But finding information on implementing ACTION_PROCESS_TEXT and adding your own actions? That’s what this post will cover.

Cross app communication -> Intent Filters

As you might expect when building functionality that crosses app boundaries, your Android Manifest and the intent filters attached to each component serve as a public API that other apps can query.

Читайте также:  Android fab speed dial

ACTION_PROCESS_TEXT is no different. You’ll add an intent filter to an Activity in your manifest:

And, if you wanted multiple actions (you overachiever, you!), you’ll need separate activities for each. As of Android 6.0.1, you’ll want to avoid adding android:exported=”false” — your action will still appear in other apps, but they’ll get a SecurityException immediately upon clicking it (the feature request to implement filtering in ACTION_PROCESS_TEXT to match the behavior of the system chooser has been marked FutureRelease and fixed internally).

Note that the android:label of your Activity will show up as the action in the text selection toolbar so ensure it is short, an action verb, and recognizable as something iconic with your app. For example, Google Translate uses ‘Translate’ as it is a less common action (how many people have multiple translation apps installed?), while Wikipedia uses ‘Search Wikipedia’ as searching may be a much more common action for many apps.

Getting the selected text

Once you get your intent filter set up, other apps will already be able to start your activity by selecting text and choosing your action from the text selection toolbar. But that doesn’t add any value unless you actually look at the text that was selected.

That’s where EXTRA_PROCESS_TEXT comes in: it is a CharSequence included in the Intent that represents what text was selected. Don’t be deceived — even though you are using a text/plain intent filter, you’ll get the full CharSequence with any Spannables included, so don’t be surprised if you notice some styling if you use the CharSequence directly in your app (you can always call toString() to remove all formatting).

Therefore your onCreate() method may look something like:

With one caveat if you are using android:launchMode=”singleTop”, then you’ll also want to process text in onNewIntent() as well — a common practice is to have both onCreate() and onNewIntent() call a single handleIntent() method you create.

And that’s about all you’d need if you are using ACTION_PROCESS_TEXT as an entryway into your app: what you do with it after that point is up to you.

Returning a result

There’s one other extra included in the ACTION_PROCESS_TEXT Intent though: EXTRA_PROCESS_TEXT_READONLY. This boolean extra denotes whether the selected text you just received can be edited by the user (such as would be the case in an EditText).

You’d retrieve the extra with code such as

You can use this as a hint to offer the ability to return altered text to the sending app, replacing the selected text. This works as your Activity was actually started with startActivityForResult() — you’ll be able to return a result by calling setResult() at any time prior to your Activity finishing:

You could imagine a button to ‘Replace’ would call setResult() followed by finish() to return back to the calling Activity.

Common questions

Before you start writing responses, here’s some common questions about ACTION_PROCESS_TEXT:

Q: Can I trigger a Service with ACTION_PROCESS_TEXT?

A: Not directly — the system only looks for Activities that contain the correct intent filter. That doesn’t mean you can’t have your Activity launch a Service using a theme of Theme.Translucent.NoTitleBar or even Theme.NoDisplay (as long as you immediately finish the Activity), but make sure you have some user visible hint that their action was received — a notification starting, a Toast, etc.

Q: Can I trigger it only for certain types of text?

A: Nope. Your option will appear every time anyone selects text. Of course, chances are users won’t select an option to ‘Translate’ unless they want to translate, etc., but I’d be careful to code defensively as you cannot be sure what type of text context you’ll receive.

Q: So should every app implement ACTION_PROCESS_TEXT? Wouldn’t that be madness?

A: Yes, that would be madness and no, not every app should implement ACTION_PROCESS_TEXT. Make sure any actions you implement are universal and truly useful to users who have your app installed.

Learn more

Besides the aforementioned Wikipedia and Google Translate which already contain good, real world examples, you can also check out the ApiDemos app installed on Marshmallow emulators or look at the code directly.

Join the discussion on the Google+ post and follow the Android Development Patterns Collection for more!

Источник

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