Resaltador de texto en Android

Text Highlighter es una de las funciones populares en la mayoría de las aplicaciones. Puede ver esta función en la aplicación de mantenimiento de notas o en cualquier aplicación educativa. La función principal de esta característica es que resalta la palabra buscada en cualquier documento. En este artículo, vamos a ver cómo implementar Text Highlighter en nuestra aplicación de Android. qué

Text Highlighter in Android Sample GIF

Aplicación de resaltador de texto 

  • La característica principal de usar este resaltador de texto es que resalta la palabra buscada en su aplicación.
  • Le dice cuánto tiempo se repite la palabra buscada y se resalta.
  • Se utiliza para la investigación de palabras clave en una aplicación.

Atributos importantes

Atributos

Descripción

.establecerColor de fondo() Úselo para configurar el Color de fondo.
.setForegroundColor() Úselo para establecer el color del texto.
.addTarget() Úselo para buscar una palabra de cierto documento.
.destacar() Use para resaltar el texto buscado.

Implementación paso a paso

Paso 1: crear un nuevo proyecto

Para crear un nuevo proyecto en Android Studio, consulte Cómo crear/iniciar un nuevo proyecto en Android Studio . Tenga en cuenta que seleccione Java como lenguaje de programación.

Paso 2: agregue la dependencia de la biblioteca Text Highlighter en el archivo build.gradle

Luego navegue a los scripts de Gradle y luego al nivel de build.gradle (Módulo) . Agregue la siguiente línea en el archivo build.gradle en la sección de dependencias.

implementación ‘com.xeoh.android:text-resaltador:1.0.3’

Ahora haga clic en Sincronizar ahora sincronizará todos sus archivos en build.gradle().

Paso 3: cree un nuevo resaltador de texto en su archivo activity_main.xml

actividad_principal.xml actividad_principal.xml

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    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"
    tools:context=".MainActivity">
  
    <!--Scroll view for scrolling-->
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true">
          
        <!--Linear layout to arrange elements one below another-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="30dp">
  
            <!--TextView to display text-->
            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:text="Android is a mobile operating system based on a modified version of the Linux kernel and other open source software, designed primarily for touchscreen mobile devices such as smartphones and tablets. Android is developed by a consortium of developers known as the Open Handset Alliance and commercially sponsored by Google. It was unveiled in November 2007, with the first commercial Android device launched in September 2008.
  
                              It is free and open source software; its source code is known as Android Open Source Project (AOSP), which is primarily licensed under the Apache License. However most Android devices ship with additional proprietary software pre-installed,[10] most notably Google Mobile Services (GMS)[11] which includes core apps such as Google Chrome, the digital distribution platform Google Play and associated Google Play Services development platform. About 70 percent of Android smartphones run Google's ecosystem;[12] competing Android ecosystems and forks include Fire OS (developed by Amazon) or LineageOS. However the 'Android' name and logo are trademarks of Google which impose standards to restrict 'uncertified' devices outside their ecosystem to use Android branding.[13][14]
  
                              The source code has been used to develop variants of Android on a range of other electronics, such as game consoles, digital cameras, portable media players, PCs and others, each with a specialized user interface. Some well known derivatives include Android TV for televisions and Wear OS for wearables, both developed by Google. Software packages on Android, which use the APK format, are generally distributed through proprietary application stores like Google Play Store, Samsung Galaxy Store, and Huawei AppGallery, or open source platforms like Aptoide or F-Droid.
  
                              Android has been the best-selling OS worldwide on smartphones since 2011 and on tablets since 2013. As of May 2017, it has over two billion monthly active users, the largest installed base of any operating system, and as of August 2020, the Google Play Store features over 3 million apps.[15] The current stable version is Android 11, released on September 8, 2020. " />
        </LinearLayout>
    </ScrollView>
  
    <!--Button to search text-->
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/search"
        android:layout_centerInParent="true"
        android:layout_margin="20dp"
        android:padding="10dp"
        android:text="Search" />
  
    <!--EditText to give text input-->
    <EditText
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp"
        android:ems="10"
        android:hint="Search"
        android:inputType="text"
        android:text="" />
      
</RelativeLayout>

Paso 4: trabajar con el archivo MainActivity.java

Vaya al archivo MainActivity.java y consulte el siguiente código. A continuación se muestra el código del archivo MainActivity.java . Se agregan comentarios dentro del código para comprender el código con más detalle.

Java

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
  
import androidx.appcompat.app.AppCompatActivity;
  
import com.xeoh.android.texthighlighter.TextHighlighter;
  
public class MainActivity extends AppCompatActivity {
  
    // Variable for button,
    // edit text and text view given
    Button button;
    EditText editText;
    TextView textView;
      
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Accepted through Id's
        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.search);
        textView = (TextView) findViewById(R.id.textView);
          
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new TextHighlighter()
                        .setBackgroundColor(Color.parseColor("#FFFF00"))
                        .setForegroundColor(Color.GREEN)
                        .addTarget(textView)
                        .highlight(editText.getText().toString(), TextHighlighter.BASE_MATCHER);
            }
        });
    }
}

Paso 5: trabajar con el archivo AndroidManifest.xml

Agregue la siguiente línea al archivo AndroidManifest.xml dentro de la etiqueta <actividad> .

android:windowSoftInputMode=”ajustarNada|estadoOculto”>

A continuación se muestra el código completo del archivo AndroidManifest.xml .

XML

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.emoji_slider">
  
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Emoji_slider">
        <activity android:name=".MainActivity"
                    
            android:windowSoftInputMode="adjustNothing|stateHidden">
            
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
  
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
  
</manifest>

Producción:

Publicación traducida automáticamente

Artículo escrito por chinmaymunje96 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *