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 texto
en 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 texto
elemento al diseño, con unandroide:texto
atributo 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_principal
el diseño solo tiene unVista de texto
en 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 texto
muestra un texto, establecido por elandroide:texto
atributo. debido a laresumir contenido
valores de ancho y alto, el tamaño de esteVista de texto
estará 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/SimpleText
edición deActividad principal
solo 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 simple
edició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 texto
El widget está disponible en la categoría "Común" de la Paleta en el editor de diseño gráfico de Android Studio:
(también aparece en la categoría “Texto”)
Si desea agregar unVista de texto
a un diseño, simplemente arrastre elVista de texto
desde 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 texto
configurará 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:
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:
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:
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.xml
por defecto), y quevalores/
directorio en el que debe ir la cadena (valores
por 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 elTextoSimple
proyectos, elVista de texto
tiene unandroide:texto
atributo establecido en el@cadena/hola
recurso de cadena
Edición de la identificación
El atributo "id" le permitirá cambiar elandroide: identificación
valor del widget:
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 elTextoSimple
proyectos, elVista de texto
tieneHola
por el contenido de su campo ID, lo que da como resultadoandroid:id="@+id/hola"
en el XML.
Atributos notables de TextView
Vista de texto
tiene muchos otros atributos de relevancia para las etiquetas, tales como:
-
Android: tipo de letra
para establecer el tipo de letra que se utilizará para la etiqueta (por ejemplo,minivan
) -
Android: estilo de texto
para indicar que el tipo de letra debe estar en negrita (atrevido
), cursiva (itálico
) o negrita y cursiva (negrita cursiva
) -
Android: color de texto
para establecer el color del texto de la etiqueta, en formato hexadecimal RGB (por ejemplo,#FF0000
para rojo), formato hexadecimal ARGB (p. ej.,#88FF0000
para 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". ElTextoSimple
aplicación establece eltamano del texto
,estilo de texto
, yrelleno
atributos