Demostración de desarrollo de Android: TextView muestra imágenes y texto al mismo tiempo, y muestra varios colores al mismo tiempo

1. Efectos esperados

        1. En un control TextView de Android, el texto y las imágenes se muestran al mismo tiempo, como se muestra en la siguiente figura. Una o más imágenes se intercalan entre el texto.

        2. En un control TextView de Android, se muestran varios colores al mismo tiempo. Como se muestra en la figura siguiente, un texto muestra dos colores diferentes.

2. Método de implementación

        Ya sea que TextView muestre imágenes y texto al mismo tiempo, o muestre varios colores al mismo tiempo, se requiere un objeto Html ImageGetter. La obtención de este objeto se puede lograr mediante el siguiente código:

private Html.ImageGetter getImageGetter() {
    return source -> {
        Drawable drawable = getDrawable(Integer.parseInt(source));
        drawable.setBounds(0, 0, 60, 60);
        return drawable;
    };
}

        No entiendo los parámetros anteriores. No es necesario cambiarlos de forma predeterminada. A menos que los llame y aparezca una excepción, puede conectarse en línea para ver cómo configurarlos adecuadamente.

        1. Muestra imágenes y texto al mismo tiempo. Idea: inserte el recurso de imagen en la cadena mediante etiquetas html y luego TextView muestra la cadena con la imagen a través de setText. De la siguiente manera (tv_1 es el control TextView que definí):

// 设置文本和图片
StringBuffer str = new StringBuffer();
str.append("故人西辞黄鹤楼");
str.append("<img src='" + R.mipmap.yellow_crane_tower + "'>");
str.append(",");
str.append("烟花三月下扬州。");

// 在文本控件中显示
tv_1.setText(Html.fromHtml(str.toString(), getImageGetter(), null));

        2. Mostrar varios colores al mismo tiempo Idea: Inserte el color del texto en la cadena a través de etiquetas html, y luego TextView muestra la cadena con diferentes colores a través de setText. De la siguiente manera (tv_2 es ​​el control TextView que definí):

// 设置文本及其颜色
StringBuffer str = new StringBuffer();
str.append("故人西辞黄鹤楼,");
str.append("<font color='#0000FF'>" + "烟花三月下扬州。" + "</font>");

// 在文本控件中显示
tv_2.setText(Html.fromHtml(str.toString(), getImageGetter(), null));

3. Efectos reales

        Puede ver que en los dos controles TextView a continuación, se ha logrado la visualización simultánea de imágenes y texto, así como la visualización simultánea de dos colores diferentes.

 

4. Código completo

        Código de actividad:

package com.cs.blackbox;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;

public class TextViewFunctionTestActivity extends AppCompatActivity {
    // 初始化界面
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_view_function_test);
        demo_1();
        demo_2();
    }

    // 同时显示图片和文本
    private void demo_1() {
        // 获取文本控件
        TextView tv_1 = findViewById(R.id.tft_tv_demo_1);
        // 设置文本和图片
        StringBuffer str = new StringBuffer();
        str.append("故人西辞黄鹤楼");
        str.append("<img src='" + R.mipmap.yellow_crane_tower + "'>");
        str.append(",");
        str.append("烟花三月下扬州。");
        // 在文本控件中显示
        tv_1.setText(Html.fromHtml(str.toString(), getImageGetter(), null));
    }

    // 同时显示多种颜色
    private void demo_2() {
        // 获取文本控件
        TextView tv_2 = findViewById(R.id.tft_tv_demo_2);
        // 设置文本及其颜色
        StringBuffer str = new StringBuffer();
        str.append("故人西辞黄鹤楼,");
        str.append("<font color='#0000FF'>" + "烟花三月下扬州。" + "</font>");
        // 在文本控件中显示
        tv_2.setText(Html.fromHtml(str.toString(), getImageGetter(), null));
    }

    // 获取一个Html ImageGetter
    @SuppressLint("UseCompatLoadingForDrawables")
    private Html.ImageGetter getImageGetter() {
        return source -> {
            Drawable drawable = getDrawable(Integer.parseInt(source));
            drawable.setBounds(0, 0, 60, 60);
            return drawable;
        };
    }
}

        Código de diseño XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="16dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="16dp"
    android:orientation="vertical"
    tools:context=".TextViewFunctionTestActivity">
    <TextView
        android:id="@+id/tft_tv_demo_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/app_black"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/tft_tv_demo_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:textColor="@color/app_black"
        android:textSize="24sp" />
</LinearLayout>

        Archivo de imagen yellow_crane_tower: simplemente descargue una imagen de Internet y reemplácela.

5. Materiales de referencia

        Reescriba ImageGetter para permitir que TextView cargue de forma asincrónica contenido html que contenga imágenes

        ImageGetter muestra imágenes en HTML

        Interfaz ImageGetter de clase HTML

Supongo que te gusta

Origin blog.csdn.net/qq_36158230/article/details/132539204
Recomendado
Clasificación