Android copy text from textview

TextView

Компонент TextView предназначен для отображения текста без возможности редактирования его пользователем, что видно из его названия (Text — текст, view — просмотр).

Находится в разделе Texts.

TextView — один из самых используемых компонентов. С его помощью пользователю удобнее ориентироваться в программе. По сути, это как таблички: Руками не трогать, По газону не ходить, Вход с собаками воспрещен, Часы работы с 9.00 до 18.00 и т.д., и служит для представления пользователю описательного текста.

Для отображения текста в TextView в файле разметки используется атрибут android:text, например:

Такой подход является нежелательным. Рекомендуется всегда использовать текстовые ресурсы. В будущем эта привычка позволит вам обеспечить многоязыковую поддержку:

Программная установка текста

Программно текст можно задать методом setText():

Атрибуты

Для всех вышеперечисленных атрибутов в классе TextView есть соответствующие методы для чтения или задания соответствующих свойств.

Программно установим размеры текста при помощи setTextSize() с различными единицами измерения.

По умолчанию у компонентов TextView отсутствует фоновый цвет. Чтобы задать цвет, укажите значение Drawable для атрибута android:background. В качестве значения Drawable может использоваться изображение или XML-представление фигуры, включающий ресурс Drawable (поместить в папку res/drawable).

Программная установка фона

В некоторых случаях программисты из-за невнимательности неправильно меняют фон элемента программным способом и удивляются, почему ничего не работает.

Предположим, у вас определён в ресурсах зелёный цвет:

Следующий код будет ошибочным:

Нужно так (два варианта):

Реагируем на событие onClick

Если вы хотите, чтобы TextView обрабатывал нажатия (атрибут android:onClick), то не забывайте также использовать в связке атрибут android:clickable=»true». Иначе работать не будет!

Многострочный текст

Если вы хотите создать многострочный текст в TextView, то используйте символы \n для переноса строк.

Например, в ресурсах:

Обратите внимание, что в тексте также применяется простое форматирование.

Также перенос на новую строку можно задать в коде:

Увеличиваем интервалы между строками

Вы можете управлять интервалом между соседними строчками текста через атрибут android:lineSpacingMultiplier, который является множителем. Установите дробное значение меньше единицы, чтобы сократить интервал или больше единицы, чтобы увеличить интервал между строками.

Бой с тенью

Чтобы оживить текст, можно дополнительно задействовать атрибуты для создания эффектов тени: shadowColor, shadowDx, shadowDy и shadowRadius. С их помощью вы можете установить цвет тени и ее смещение. Во время установки значений вы не увидите изменений, необходимо запустить пример в эмуляторе или на устройстве. В следующем примере я создал тень красного цвета со смещением в 2 пикселя по вертикали и горизонтали. Учтите, что для смещения используются единицы px (пиксели), единицы dp не поддерживаются.

Программный эквивалент — метод public void setShadowLayer (float radius, float dx, float dy, int color):

Создание ссылок автоматом

У TextView есть ещё два интересных свойства Auto link (атрибут autoLink) и Links clickable (атрибут linksClickable), которые позволяют автоматически создавать ссылки из текста.

Выглядит это следующим образом. Предположим, мы присвоим элементу TextView текст Мой сайт: developer.alexanderklimov.ru и применим к нему указанные свойства.

При этом уже на этапе разработки вы увидите, что строка адреса сайта после слов Мой адрес: стала ссылкой. Если вы запустите приложение и нажмете на ссылку, то откроется браузер с указанным адресом. Вам даже не придется писать дополнительный код. Аналогично, если указать номер телефона (параметр phone), то запустится звонилка.

У ссылки есть интересная особенность — при длительном нажатии на ссылку появляется диалоговое окно, позволяющее скопировать ссылку в буфер обмена.

Атрибут autoLink позволяет комбинировать различные виды ссылок для автоматического распознавания: веб-адрес, email, номер телефона.

Цвет ссылки можно поменять через свойство Text color link (XML-атрибут textColorLink), а программно через метод setTextLinkColor().

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

Кроме константы ALL, можно также использовать Linkify.EMAIL_ADDRESSES, Linkify.MAP_ADDRESSES, Linkify.PHONE_NUMBERS. К сожалению, русские адреса не распознаются. В моём случае индекс был распознан как телефонный номер, а город и улица не стали ссылкой.

В таких случаях придётся самостоятельно добавить ссылки в текстах. Например, определим ссылку в ресурсе:

Присвоим созданный ресурс тексту в TextView и запустим пример. Сам текст будет выглядеть как ссылка, но реагировать не будет. Чтобы исправить данную проблему, добавим код:

Ссылки в тексте выглядят не совсем удобными. Есть отдельная библиотека, которая улучшает функциональность. Описание проблем и ссылка на библиотеку есть в статье A better way to handle links in TextView — Saket Narayan.

Читайте также:  4pda отключить рекламу андроид

Совет: Используйте полупрозрачность с умом

Если вам нужно установить текст полупрозрачным, то не используйте атрибут android:alpha:

Дело в том, что такой подход затрачивает много ресурсов при перерисовке.

Атрибут textColor позволяет установить полупрозрачность без потери производительности:

Выделить текст для копирования

По умолчанию, текст в TextView нельзя выделить для копирования. Но в API 11 появилась такая возможность, которая может пригодиться. Делается либо при помощи XML-атрибута android:textIsSelectable, либо через метод setTextIsSelectable().

Добавьте в разметку два компонента TextView и одно текстовое поле EditText для вставки скопированного текста. У первой текстовой метки установим возможность выделения текста декларативно.

Для второго компонента возможность выделения создадим программно.

Сделайте долгий тап на тексте в любом TextView. Увидите стандартные ползунки для выбора длины текста. Скопируйте текст, сделайте длинный тап в EditText и вставьте текст.

Источник

Скопировать текст из TextView на Android

У меня есть ListView , где каждый элемент является TextView .

Я хочу включить поведение продолжительного нажатия, аналогичное EditText , которое отображает контекстное меню по умолчанию с такими элементами, как «Выбрать все», «Вырезать все», «Скопировать все» и т.д.

Есть ли простой способ включить это для TextView ?

ОТВЕТЫ

Ответ 1

Я думаю, что у меня есть решение. Просто позвоните
registerForContextMenu(yourTextView);

и ваш TextView будет зарегистрирован для получения событий контекстного меню.

Затем переопределите onCreateContextMenu в Activity :

Надеюсь, это поможет вам и всем, кто ищет способ скопировать текст из TextView

Ответ 2

Собственно, вам не нужно разрабатывать эту функцию самостоятельно. Вам просто нужно использовать EditText вместо TextView, пока вы установите для android: editable EditText значение false. Мой код здесь:

Вы можете просто щелкнуть по элементу и выбрать текст, скопировать, вырезать, пропустить и т.д.

Ответ 3

Чтобы пользователи могли скопировать некоторые или все значения TextView и вставить их где-то еще,

Ответ 4

Возможно, вы захотите зарегистрировать onItemLongClickListener в своем ListView, а затем на основе выбранного элемента, предоставить пользователю все варианты, которые вы выберете.

Ответ 5

У меня есть решение, но я не совсем полезен.

Источник

Извлечение данных c TextView

Здравствуйте уважаемые форумчане.
Как извлеч значение TextView1?

Есть TextView хочу построить процедуру if then else

Текст из TextView перенести в другой TextView по нажатию Button
Люди, помогите плиз. Недавно начал ковырять программирование под Android. Хотел сделать банальную.

SQLite Android и вывод данных в TextView
Использую SQLite для хранения и доступа к данным в андроид-приложении. Задаю public final class.

Извлечение данных с сайта и загрузка этих данных в эксель
Всем доброго суток. Вопрос такого плана. Есть подраздел на сайте. В качестве примера рассмотрим.

Извлечение данных из базы данных и работа с ними
Здравствуйте! я начинающий программист и нужна ваша помощь. мне нужно написать дипломный проект. он.

Не подскажете, где именно мне нужно написать этот код?

TextView1 у вас строка или число?

Добавлено через 5 минут
А где у вас вообще этот TextView1? Для начала его нужно «найти»

ТекстView2 — это число, если можно будет использовать текст в место числа — будет супер

перед тем как вытягивать текст с textView нужно найти view по id, а потом получать текст:
типо так:

Вот в этом и вся проблема, не знаю как объявить и как написать. В андроиде и в Java новичек. Учусь. И на данный момент застрял именно тут. Не могу извлечь данные с TextView2 и проверить.

В Layout-e есть TextView2 с значем 0. При нажатии кнопки должен измениться значение TextView. Другая процедура проверяет, какое значение в TextView. Соответсвенно тому что написал: Если TextView = 1 откроется одно активити, если 2 другое.

если у вас не секретный проект, можете мне его скинуть и я вас сделаю?

Добавлено через 2 минуты
или покажите xml файл где у вас размещён textview.

Добавлено через 1 минуту
Вот, вы подключаете вьюху setContentView(R.layout.msng);
Покажите содержимое xml файла с названием «msng»

Вывод информации из базы данных Firebase в TextView
Моя задача состоит в том, чтобы вывести данные из базы данных Firebase в TextView. Вот так выглядит.

Извлечение данных из базы данных построчно
как извлечь построчно данные из базы данных так, чтобы можно было оперировать по отдельности каждой.

Извлечение данных из базы данных в dataGridView1
Я извлекаю данные следующим найденным способом: private void Form1_Load(object sender.

TextView txt = new TextView(this); — ошибка
Возникла проблема с динамическим создание TextView в цыкле, хотя в другом месте создается таким же.

Источник

Android TextView Tutorial, Variations and Customizations

Android TextView Tutorial and Examples

Let’s discuss one of the most simple and commonly used android widgets, the TextView class.

Android TextView is a User interface widget that displays basic texts.

In almost every Graphical User Interface toolkit out there, a component or control for displaying text is there. Be it the Label in Windows Forms or the JLabel in Swing .

This is because we mostly communicate via texts and these texts have to be rendered. Well the textview renders them in Android.

TextViews and labels are normally considered basic and are easy to work with.

Читайте также:  Рут права для андроид lenovo

In android textviews are actually editable though by default this is disabled. Instead it’s subclass the EditText on the other hand allows for editing.

TextView as a class resides in the android.widget package.

TextView derives from android.view.View class and implements import android.view.ViewTreeObserver.OnPreDrawListener .

TextViews can be created either programmatically or via inflation of XML.
Here are the constructors to create a TextView object programmatically.

No. Constructor
1. public TextView(Context context)
2. public TextView(Context context, AttributeSet attrs)
3. public TextView(Context context, AttributeSet attrs, int defStyleAttr)
4. public TextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

Let’s look at various TextView examples:

Creating TextView From XML Definition

Most of the time we define textviews via xml and inflate them in our activity.
Here’s a typical definition of android textview;

  • First we specify a unique id for the textview using android:id=»» attribute that will be used to reference the textview from C# code.
  • We then define the layout width( android:layout_width=»» ) and height( android:layout_height=»» ) of the textview.
  • Next we specify the text via the android:text=»» attribute.

We then come to our MainActivity ‘s OnCreate() method. OnCreate() method is a lifecycle callback that gets called when the activity in android has been created.

Normally we make view initializations here since the activity has been created.

But first we make sure that the following method has been invoked:

The above method will inflate our `activity_main.axml` layout and set it as the layout of our activity. This layout has to be inflated first since it contains our `TextView`.

Then we come reference our `TextView`:

This will give us a textview reference which we can use to set text:

If we run the project we get:

Here’s the full source code:
activity_main.axml:

Creating TextView Programmatically as the ContentView of an Activity

It’s not mandatory that you set a layout as the content view of an activity.

You can use a view instead of inflating a layout. If anything the layouts do get inflated into a view object.

However this is only suitable for simple interfaces. if you need a complex interface with nested widgets, then you use the layout as it’s easier to write such declaratively.

First we instantiate a TextView programmatically, passing in the `Context` object:

Let’s then set the textview’s background color programmatically:

Then set the text:

And finally set the content view:

Here’s the full code. Note we don’t need an xml layout:

Here’s what we get:

Here’s another example of building a textview programmatically with several attributes being set:

Hiding a TextView

What about if you want to hide a textview. Well it’s a view so we can simply set it’s visibility to `View.GONE`:

Using TextView in a Fragment

Well just override the `onCreateView()` method of your Fragment, then first make sure the Fragment layout is inflated into a View object.

Then find the textview from that inflated view:

Then of course you can set it’s text property as you wish:

Common TextView Methods and examples

1. setText()

To set text to a textview you simply use the `setText()` method.

What about if you want to set text that has been sent from another activity:

2. setTextColor()

Let’s say we have the color in defined in the colors.xml resource, so we load the color from there using `getResources().getColor()` invokation.

You can also set color literal in hexadecimal notation(using the characters ‘0x’ followed by the hexadecimal number) like this;

This is the Opaque black color we’ve used.

However we can also set the color from the `android.Graphics.Color` class as follows:

3. setBackgroundColor()

Well we are also capable of setting the background color of a textview:

5. setGravity()
6. setTextSize()
7. setSingleLine()
8. setTypeface()
9. setId()
10. setLayoutParams()
11. How to add and Cancel Strike Through to TextView

These two methods show us how to add or cancel a strike through in a textview widget.

You just pass that textView as a parameter and we invoke the `setPaintFlags()` with the appropriate parameters. We utilize the `Paint` class, which normally holds the style and color information about how to draw geometries, text and bitmaps.

11. postDelayed()
12. How to create a Gradient TextView

2. Android TextView — Fill From StringBuilder

Android TextView and StringBuilder Example Tutorial.

How to populate a textview from a stringbuilder.

`android.widget.TextView` is a class used to render texts.

`java.lang.StringBuilder` on the other hand allows for creation of modifiable string of characters. StringBuilder is the replacemnet for `StringBuffer` class for non-concurrent use.

In this example we’ll see how to:

  • Create a StringBuilder with multiple items.
  • Render the StringBuilder items in a TextView line by line.

For this example we don’t need any XML layout. Instead we create and set an `android.view.View` object as our contentView for our activity.

Classes in Java are normally grouped into packages. So we first specify the package for our MainActivity class.

We then define the class:

We’ll then add several imports above the class:

Then make the class derive from `AppCompatActivity`.

AppCompatActivity makes your activity backword compatible with older devices.
To use it your app level build.gradle dependencies section must contain the following support library. Note the version can differ:

We then override the `onCreate()` method inside our class. This is a lifecycle callback for android that gets raised when the activity is created.
We’ll do our stuff right here.

Note that we have to call the super class onCreate() method as above and pass it the savedInstanceState.

Then we instantiate the StringBuilder class:

All these we do inside the `onCreate()` method.

Then append our data using method chaining. This is possible since each `append()` method returns an instance of the `StringBuilder`.

Then instantiate our TextView, passing in our Context object.

Then convert our StringBuilder to String using the `toString()` method so that we can display it in the TextView.

Lastly we call the `setContentView()` method of the AppCompatActivity class. This method will set our TextView as the main view of our activity.

Here’s the full source code. Note we don’t need an XML for this example.

Android AppCompatTextView

AppCompatTextView is basically a TextView which provides support to older version of the android platform with compatible features of a TextView.

Whenever you use a TextView, android may automatically use the AppCompatTextView.

This is if your project has the necessary support library dependencies.

AppCompatTextView resides in the `android.support.v7.widget` package.

This class derives from TextView:

Given that it derives from `android.widget.TextView`, this class inherits TextView’s XML attributes. Some of these attributes are inherited by TextView itself from the base View class.

Creating AppCompatTextView.

Not only can you create AppCompatTextView via the XML specifications, but you can also create them programmatically.

To do so you can use the provided public constructors.

Android does provide us three of those:

No. Constructor
1. AppCompatTextView(Context context)
2. AppCompatTextView(Context context, AttributeSet attrs)
3. AppCompatTextView(Context context, AttributeSet attrs, int defStyleAttr)

As for the methods this class does inherit them from other classes like TextView, View and Object.

We mostly render labels and text data using textviews in android. By default textviews are pretty basic and usually you have to manually parse the text to detect hashtags, links, phone numbers, emails and mentions.

However there are a couple of solutions you can use for this capability.

(a). AutoLinkTextViewV2

AutoLinkTextViewV2 is the new version of the AutoLinkTextView.

The main differences between the old and new version are

  • Fully migration to Kotlin
  • Added several new features
  • Some improvements and fixes

It supports automatic detection and click handling for

  • Hashtags (#)
  • Mentions (@)
  • URLs (http://)
  • Phone Numbers
  • Emails
  • Custom Regex

Features

  • Default support for Hashtag, Mention, Link, Phone number and Email
  • Support for custom types via regex
  • Transform url to short clickable text
  • Ability to apply multiple spans to any mode
  • Ability to set specific text color
  • Ability to set pressed state color

Step 1: Installation

This library is hosted in jcenter. The minimum API supported is API level 16.

Step 2: Layout

Then in the layout add:

Step 3: Code

Then in the code

Add one or multiple:

You can add URL transformations to transform URL into clickable texts:

Or attach a URL processor:

You can style the transformations:

You can listen to the link click event:

Setting text by the way is easy:

Read more or find full example here.

How to copy TextView content into Clipboard

In this short piece we want to look at several easy ways to copy textview content into the clipboard. For example, suppose you want to copy TextView content into an edittext for saving.

(a). Use CopyButton

CopyButton is a simple library created for just that purpose. It is free from boilerplate code and can be attached to a textview. For example you can listen to double click or long click events in a textview, then react by copying the text content of that textview.

Step 1: Installation

Install it from jitpack:

Step 2: Code

Then in the code:

Links

  1. Download the code here and follow the author here.

Creating an EmailValidator

Android AutoCompleteTextView Tutorial and Example

Validating Email Address using Regex

Oclemy

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Источник

Читайте также:  Draw the line android
Оцените статью