TextView: asignación de etiquetas (2024)

Podría decirse que el widget más simple es la etiqueta, denominada en Android comoVista de texto. Como en la mayoría de los juegos de herramientas de GUI, las etiquetas son fragmentos de texto que los usuarios no pueden editar directamente. Por lo general, se usan para identificar widgets adyacentes (p. ej., una etiqueta de "Nombre:" antes de un campo donde se completa un nombre) o mostrar otro texto de relevancia para los usuarios (p. ej., mensajes en un cuadro de diálogo emergente).

Como con cualquier widget, puede crear instancias deVista de textoen su código Java o Kotlin invocando un constructor, luego useestablecerTexto()métodos para establecer el texto que mostrará elVista de texto. Sin embargo, para las interfaces de usuario ordinarias, normalmente usará recursos de diseño XML; allí, puede agregar unVista de textoelemento al diseño, con unandroide:textoatributo para establecer el texto de la propia etiqueta.

Una vista de texto de muestra

Nuestra primera aplicación de muestra:TextoSimple- es incluso más simple que los "Hola, mundo" de antes en el libro. Elactividad_principalel diseño solo tiene unVista de textoen eso:

 androide:id="@+id/hola" xmlns:android="http://esquemas.android.com/apk/res/android" android:layout_width="resumir contenido" android:layout_height="resumir contenido" Android: relleno ="@dimen/hola_padding" androide:texto="@cadena/hola" android:textSize="@dimen/hola_tamaño" android:textStyle="atrevido" />

AVista de textomuestra un texto, establecido por elandroide:textoatributo. debido a laresumir contenidovalores de ancho y alto, el tamaño de esteVista de textoestará determinado por:

  • El texto que estamos poniendo en él (androide:texto)
  • El tamaño de fuente de ese texto (Android:Tamaño del texto)
  • El estilo de fuente de ese texto (Android: estilo de texto)
  • El acolchado que le ponemos (Android: relleno)

ElSamplerJ/SimpleTextedición deActividad principalsolo muestra este diseño, a través desetContentView():

paquete com.commonsware.jetpack.samplerj.simpletext;importar androidx.appcompat.app.AppCompatActivity;importar android.os.Bundle;público clase Actividad principal extiende AppCompatActivityAppCompatActivity { @Anular protegido vacío enCrear(Manojo estado de instancia guardado) { súper.enCrear(estado de instancia guardado); setContentView(R.disposición.actividad_principal); }}

…mientraselMuestreador/Texto simpleediciónhace lo mismo, pero en Kotlin en lugar de Java:

paquete com.commonsware.jetpack.sampler.simpletextimportar androidx.appcompat.app.AppCompatActivityimportar android.os.Bundleclase Actividad principal : AppCompatActivityAppCompatActivity() { anular divertido enCrear(estado de instancia guardado: Manojo?) { súper.enCrear(estado de instancia guardado) setContentView(R.disposición.actividad_principal) }}

Editor de diseño gráfico de Android Studio

ElVista de textoEl widget está disponible en la categoría "Común" de la Paleta en el editor de diseño gráfico de Android Studio:

TextView: asignación de etiquetas (1)

(también aparece en la categoría “Texto”)

Si desea agregar unVista de textoa un diseño, simplemente arrastre elVista de textodesde la Paleta a un archivo de diseño en el área de edición principal para agregar el widget al diseño. O bien, arrástrelo sobre la parte superior de algún contenedor que vea en el panel Árbol de componentes del editor para agregarlo como elemento secundario de ese contenedor específico.

Al hacer clic en el nuevoVista de textoconfigurará el panel Atributos con los diversos atributos del widget, listo para que los cambie según sea necesario.

Edición del texto

El atributo “Texto” le permitirá elegir o definir un recurso de cadena para que sirva como texto a mostrar:

TextView: asignación de etiquetas (2)

El "texto" con un icono de llave inglesa le permite proporcionar un texto separado que se mostrará en la vista previa, pero que su aplicación no utilizará en el tiempo de ejecución.

Puede escribir una cadena literal directamente en la fila del panel Atributos, o puede hacer clic en el botón "O" a la derecha del campo para elegir un recurso de cadena:

TextView: asignación de etiquetas (3)

Puede resaltar uno de esos recursos y hacer clic en "Aceptar" para usarlo. O, hacia la parte superior izquierda de ese cuadro de diálogo, hay un menú desplegable "+". Al ver los recursos de cadena, ese menú desplegable ofrecerá las opciones "Archivo de recursos de cadena" y "Valor de cadena". Elegir la opción "Valor de cadena" le permitirá definir un nuevo recurso de cadena a través de otro cuadro de diálogo:

TextView: asignación de etiquetas (4)

Puede darle un nombre a su nuevo recurso de cadena, el texto real de la cadena en sí, el nombre de archivo en el que debe residir el recurso de cadena (cadenas.xmlpor defecto), y quevalores/directorio en el que debe ir la cadena (valorespor defecto). También elegirá el "conjunto de origen"; por ahora, eso solo seráprincipal. Una vez que acepte el cuadro de diálogo, su nuevo recurso de cadena se aplicará a suVista de texto.

En elTextoSimpleproyectos, elVista de textotiene unandroide:textoatributo establecido en el@cadena/holarecurso de cadena

Edición de la identificación

El atributo "id" le permitirá cambiar elandroide: identificaciónvalor del widget:

TextView: asignación de etiquetas (5)

El valor que ingrese aquí es lo que va después del@+id/porción (por ejemplo,vista de texto2). Esto funciona para todos los widgets, no soloVista de texto.

En elTextoSimpleproyectos, elVista de textotieneHolapor el contenido de su campo ID, lo que da como resultadoandroid:id="@+id/hola"en el XML.

Atributos notables de TextView

Vista de textotiene muchos otros atributos de relevancia para las etiquetas, tales como:

  1. Android: tipo de letrapara establecer el tipo de letra que se utilizará para la etiqueta (por ejemplo,minivan)
  2. Android: estilo de textopara indicar que el tipo de letra debe estar en negrita (atrevido), cursiva (itálico) o negrita y cursiva (negrita cursiva)
  3. Android: color de textopara establecer el color del texto de la etiqueta, en formato hexadecimal RGB (por ejemplo,#FF0000para rojo), formato hexadecimal ARGB (p. ej.,#88FF0000para un rojo translúcido), o como una referencia a un recurso de color (por ejemplo,@color/colorAcento)

Estos atributos, como la mayoría de los demás, se pueden modificar a través del panel Atributos, aunque muchos de ellos se encuentran en la sección "Todos los atributos". ElTextoSimpleaplicación establece eltamano del texto,estilo de texto, yrellenoatributos

TextView: asignación de etiquetas (2024)

FAQs

What is the purpose of TextView? ›

Android TextView is a user interface which displays the text to the user. A simple XML code of TextView in a layout is shown below.

How to make TextView responsive in android? ›

You can either use the framework or Support Library to set up the autosizing of TextView programmatically or in XML. To set the XML attributes, you can also use the Properties window in Android Studio. There are three ways you can set up the autosizing of TextView , described in the sections that follow: Default.

How to make a TextView marquee? ›

Navigate to the app > res > layout > activity_main. xml and add the below code to that file. TextView is used here to add the text which we want to display on the screen. Here we have used android:ellipsize=”marquee” to add a marquee to our text and android:singleLine=”true” so that our text will show only in one line.

Which method is used to set the text in a TextView? ›

SetText(String, TextView+BufferType)

Sets the text to be displayed using a string resource identifier.

What are attributes of TextView? ›

XML Attributes of TextView in Android
AttributesDescription
android:textSizeSets font size of the text.
android:textStyleSets style of the text. For example, bold, italic, bolditalic.
android:typefaceSets typeface or font of the text. For example, normal, sans, serif etc
android:widthSets width of the TextView.
29 more rows
Oct 1, 2021

What is text view and edit text? ›

TextView is the widget used when you want the user to View the Text (such as a label, etc) and EditText used when you want the user to be able to edit the text. The text in either widget can be set programmatically or via xml using the android:text parameter.

What is the difference between text view and Edit view in android? ›

EditText is used for user input. TextView is used to display text and is not editable by the user. TextView can be updated programatically at any time.

How to remove drawable from TextView in android programmatically? ›

Use 0 or null if you do not want a Drawable there.

textView. setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);

What is responsive view activity? ›

Responsive/adaptive layouts provide an optimized user experience regardless of screen size. Implement responsive/adaptive layouts to enable your view‑based app to support all display sizes, orientations, and configurations, including resizable configurations such as multi-window mode.

What is TextView in android? ›

A TextView displays text to the user and optionally allows them to edit it. A TextView is a complete text editor, however the basic class is configured to not allow editing.

How do I make a TextView single line? ›

You should use android:maxLines="1" in your TextView tag.

How do I add a bullet symbol in TextView? ›

You may try BulletSpan as described in Android docs. This is how i ended up doing it. (almost) all of the options are about using html tags. you can use drawables for your TextView if it has only one line of text.

What is the difference between TextView and EditText? ›

The names of them are pretty self explanatory. TextView is the widget used when you want the user to View the Text (such as a label, etc) and EditText used when you want the user to be able to edit the text. The text in either widget can be set programmatically or via xml using the android:text parameter.

How to use TextView in android? ›

Step by Step Implementation
  1. Step 1: Create an Empty Activity Project.
  2. Step 2: Working with the activity_main.xml file.
  3. To implement the UI of the activity invoke the following code inside the activity_main. ...
  4. Output UI:
  5. The above four types of faces are to be invoked under the “typeFace” attribute of the TextView in XML.
Apr 16, 2024

What is the difference between TextView and textfield? ›

UITextField : For entering a single line of text. Use secure entry for sensitive data such as passwords. UITextView : For displaying or entering one or more lines of text. Selection, editing, and scrolling are possible.

What is the difference between TextView and PlainText? ›

Plaintext is nothing but the Edittext. It has changed the name in Android studio but if you check into Design view you will get to know that it still has name of Edittext only. Textview : should be used for uneditable text which user wants to read but not to manipulate. e.g. News, Articles, Blogs.

Top Articles
Latest Posts
Article information

Author: Edmund Hettinger DC

Last Updated:

Views: 6445

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Edmund Hettinger DC

Birthday: 1994-08-17

Address: 2033 Gerhold Pine, Port Jocelyn, VA 12101-5654

Phone: +8524399971620

Job: Central Manufacturing Supervisor

Hobby: Jogging, Metalworking, Tai chi, Shopping, Puzzles, Rock climbing, Crocheting

Introduction: My name is Edmund Hettinger DC, I am a adventurous, colorful, gifted, determined, precious, open, colorful person who loves writing and wants to share my knowledge and understanding with you.