Puedo subrayar texto en un diseño de Android?
-
25-09-2019 - |
Pregunta
Cómo puedo definir subrayó texto en un diseño de Android xml
archivo?
Solución
Se puede lograr si está utilizando un recurso de cadena de archivo XML, que soporte HTML etiquetas como <b></b>
, <i></i>
y <u></u>
.
<resources>
<string name="your_string_here">This is an <u>underline</u>.</string>
</resources>
Si quieres algo subrayado por el uso de código:
TextView textView = (TextView) view.findViewById(R.id.textview);
SpannableString content = new SpannableString("Content");
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
textView.setText(content);
Otros consejos
Puede intentar con
textview.setPaintFlags(textview.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
El "aceptado" respuesta anterior no de trabajo (cuando se intenta utilizar la cadena como textView.setText(Html.fromHtml(String.format(getString(...), ...)))
.
Como se indica en la documentación que debe escapar corchete de apertura (html entidad codificada) de las etiquetas interiores con <
, por ejemplo, resultado debe ser similar a:
<resource>
<string name="your_string_here">This is an <u>underline</u>.</string>
</resources>
A continuación, en el código se puede ajustar el texto con:
TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(String.format(getString(R.string.my_string), ...)));
contenido del archivo strings.xml:
<resource>
<string name="my_text">This is an <u>underline</u>.</string>
</resources>
archivo XML Layout shold utilizar el recurso de cadena anteriormente con debajo propiedades de Vista de Texto, como se muestra a continuación:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="@string/my_text"
android:selectAllOnFocus="false"
android:linksClickable="false"
android:autoLink="all"
/>
Para el botón de Vista de Texto y esta es la manera más fácil:
botón:
Button button = (Button) findViewById(R.id.btton1);
button.setPaintFlags(button.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Textview:
TextView textView = (TextView) findViewById(R.id.textview1);
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Una solución línea
myTextView.setText(Html.fromHtml("<p><u>I am Underlined text</u></p>"));
Es poco tarde, pero podría ser útil para alguien.
El más reciente enfoque de dibujo en el texto subrayado es descrito por Romain Guy en medio con disponibilidad de código fuente en GitHub.Esta aplicación de ejemplo expone dos posibles implementaciones:
- Un Camino basado en la aplicación que requiere de la API de nivel 19
- Una Región basado en la aplicación que requiere de la API de nivel 1
En Kotlin función de extensión se puede utilizar. Esto sólo se puede utilizar desde el código, no XML.
fun TextView.underline() {
paintFlags = paintFlags or Paint.UNDERLINE_TEXT_FLAG
}
Uso:
tv_change_number.underline()
tv_resend_otp.underline()
Sé que esto es una respuesta tardía, pero se me ocurrió una solución que funciona bastante bien ... Me tomó la respuesta de Anthony Forloney para subrayar texto en código y crea una subclase de TextView que los mangos de que para usted. A continuación, sólo puede utilizar la subclase en XML cada vez que desee tener un TextView subrayado.
Esta es la clase que he creado:
import android.content.Context;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created with IntelliJ IDEA.
* User: Justin
* Date: 9/11/13
* Time: 1:10 AM
*/
public class UnderlineTextView extends TextView
{
private boolean m_modifyingText = false;
public UnderlineTextView(Context context)
{
super(context);
init();
}
public UnderlineTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
init();
}
public UnderlineTextView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init();
}
private void init()
{
addTextChangedListener(new TextWatcher()
{
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
//Do nothing here... we don't care
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
//Do nothing here... we don't care
}
@Override
public void afterTextChanged(Editable s)
{
if (m_modifyingText)
return;
underlineText();
}
});
underlineText();
}
private void underlineText()
{
if (m_modifyingText)
return;
m_modifyingText = true;
SpannableString content = new SpannableString(getText());
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
setText(content);
m_modifyingText = false;
}
}
Ahora ... cada vez que desee crear un TextView subrayada en XML, que acaba de hacer lo siguiente:
<com.your.package.name.UnderlineTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="This text is underlined"
android:textColor="@color/blue_light"
android:textSize="12sp"
android:textStyle="italic"/>
Me han añadido opciones adicionales en este fragmento de XML para mostrar que mi ejemplo trabaja con cambiar el color del texto, tamaño y estilo ...
Espero que esto ayude!
revisar el estilo de botón que se pulse subrayada:
<TextView
android:id="@+id/btn_some_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btn_add_contact"
android:textAllCaps="false"
android:textColor="#57a0d4"
style="@style/Widget.AppCompat.Button.Borderless.Colored" />
strings.xml:
<string name="btn_add_contact"><u>Add new contact</u></string>
Resultados:
Una forma más limpia en lugar de la Red
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
método es usar
textView.getPaint().setUnderlineText(true);
Y si usted necesita para convertir más tarde fuera subrayado para ese punto de vista, como en una vista reutilizado en un RecyclerView, textView.getPaint().setUnderlineText(false);
Sólo tiene que utilizar el atributo de archivo de recurso de cadena por ejemplo.
<string name="example"><u>Example</u></string>
He utilizado este dibujable XML para crear un fondo de la frontera y se aplica el dibujable como el fondo de mi TextView
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle" >
<solid android:color="@android:color/transparent" />
</shape>
</item>
<item android:top="-5dp" android:right="-5dp" android:left="-5dp">
<shape>
<solid android:color="@android:color/transparent" />
<stroke
android:width="1.5dp"
android:color="@color/pure_white" />
</shape>
</item>
</layer-list>
A simple y solución flexible en XML:
<View
android:layout_width="match_parent"
android:layout_height="3sp"
android:layout_alignLeft="@+id/your_text_view_need_underline"
android:layout_alignRight="@+id/your_text_view_need_underline"
android:layout_below="@+id/your_text_view_need_underline"
android:background="@color/your_color" />
Joder, es muy sencillo de utilizar
TextView tv = findViewById(R.id.tv);
tv.setText("some text");
Vista de Texto toda Subrayado
setUnderLineText(tv, tv.getText().toString());
Subrayado alguna parte de TextView
setUnderLineText(tv, "some");
El apoyo también del niño TextView como EditarTexto, Botón, Casilla de verificación
public void setUnderLineText(TextView tv, String textToUnderLine) {
String tvt = tv.getText().toString();
int ofe = tvt.indexOf(textToUnderLine, 0);
UnderlineSpan underlineSpan = new UnderlineSpan();
SpannableString wordToSpan = new SpannableString(tv.getText());
for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
ofe = tvt.indexOf(textToUnderLine, ofs);
if (ofe == -1)
break;
else {
wordToSpan.setSpan(underlineSpan, ofe, ofe + textToUnderLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
}
}
}
otra solución es una crear una vista personalizada que se extienden TextView como se muestra abajo
public class UnderLineTextView extends TextView {
public UnderLineTextView(Context context) {
super(context);
this.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
}
public UnderLineTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
}
}
y simplemente añadir a XML como se muestra a continuación
<yourpackage.UnderLineTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="underline text"
/>
probar este código
en XML
<resource>
<string name="my_text"><![CDATA[This is an <u>underline</u>]]></string>
</resources>
en el código
TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(getString(R.string.my_text)));
Buena suerte!
Samuel respuesta 's:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!--https://stackoverflow.com/a/40706098/4726718-->
<item
android:left="-5dp"
android:right="-5dp"
android:top="-5dp">
<shape>
<stroke
android:width="1.5dp"
android:color="@color/colorAccent" />
</shape>
</item>
</layer-list>
- Ir al archivo de recursos strings.xml
- Añadir una cadena en el archivo de recursos con una etiqueta HTML subrayado cuando sea necesario.
- Llame a la ID de recurso de cadena en su código Java de la siguiente manera:
sampleTextView.setText(R.string.sample_string);
- La salida debe tener la palabra "Stackoverflow" subrayó.
Además, el siguiente código no se imprimirá el subrayado:
String sampleString = getString(R.string.sample_string);
sampleTextView.setText(sampleString);
En su lugar, utilice el siguiente código para retener formato de texto enriquecido:
CharSequence sampleString = getText(R.string.sample_string);
sampleTextView.setText(sampleString);
"Puede utilizar cualquiera getString (int) o getText (int) para recuperar una cadena. GetText (int) retiene cualquier rica estilo del texto aplicada a la cuerda." documentación de Android.
Consulte la documentación: https://developer.android. com / guía / temas / recursos / string-resource.html
Espero que esto ayude.
La parte superior votado es correcto y sencillo. Sin embargo, a veces es posible que no funciona por alguna fuente, pero trabajando para otros. (¿Qué problema que acabo de encontrar cuando se trata de China.)
La solución es no utilizar "WRAP_CONTENT" sólo para su TextView, porque no hay más espacio para dibujar la línea. Es posible conjunto fijo altura a su TextView, o el uso de Android:. PaddingVertical con WRAP_CONTENT
HtmlCompat.fromHtml(
String.format(context.getString(R.string.set_target_with_underline)),
HtmlCompat.FROM_HTML_MODE_LEGACY)
<string name="set_target_with_underline"><u>Set Target<u> </string>
Tenga en cuenta el símbolo de escape en el archivo xml
Yo tenía un problema en el que estoy usando una fuente personalizada y el subrayado creada con el truco archivo de recursos (<u>Underlined text</u>
) funcionaba, pero Android logró transformar el subrayado a una especie de artesa huelga.
utiliza esta respuesta a dibujar un borde debajo de la Vista de Texto a mí mismo: https://stackoverflow.com/a/10732993/664449 . Obviamente, esto no funciona para texto subrayado parcial o texto multilined.