Un cuadro de diálogo de búsqueda impresionante y personalizable con opciones de búsqueda integradas.
Primero agregue jitpack al archivo build.gradle de su proyecto
allprojects {
repositories {
.. .
maven { url " https://jitpack.io " }
}
}
Luego agregue la dependencia en el archivo build.gradle de los módulos.
dependencies {
implementation ' com.github.mirrajabi:search-dialog:1.2.4 '
}
Si solo desea utilizar el cuadro de diálogo de búsqueda simple, primero debe proporcionar elementos que se puedan buscar. para lograr esto, debes implementar Searchable en tu modelo.
puedes ver SampleSearchModel, por ejemplo:
public class SampleSearchModel implements Searchable {
private String mTitle ;
public SampleSearchModel ( String title ) {
mTitle = title ;
}
@ Override
public String getTitle () {
return mTitle ;
}
public SampleSearchModel setTitle ( String title ) {
mTitle = title ;
return this ;
}
}
ahora genera algunas opciones de búsqueda en tu actividad:
private ArrayList < SampleSearchModel > createSampleData (){
ArrayList < SampleSearchModel > items = new ArrayList <>();
items . add ( new SampleSearchModel ( "First item" ));
items . add ( new SampleSearchModel ( "Second item" ));
items . add ( new SampleSearchModel ( "Third item" ));
items . add ( new SampleSearchModel ( "The ultimate item" ));
items . add ( new SampleSearchModel ( "Last item" ));
items . add ( new SampleSearchModel ( "Lorem ipsum" ));
items . add ( new SampleSearchModel ( "Dolor sit" ));
items . add ( new SampleSearchModel ( "Some random word" ));
items . add ( new SampleSearchModel ( "guess who's back" ));
return items ;
}
entonces solo necesita agregar las siguientes líneas donde desea mostrar el cuadro de diálogo:
new SimpleSearchDialogCompat ( MainActivity . this , "Search..." ,
"What are you looking for...?" , null , createSampleData (),
new SearchResultListener < SampleSearchModel >() {
@ Override
public void onSelected ( BaseSearchDialogCompat dialog ,
SampleSearchModel item , int position ) {
// If filtering is enabled, [position] is the index of the item in the filtered result, not in the unfiltered source
Toast . makeText ( MainActivity . this , item . getTitle (),
Toast . LENGTH_SHORT ). show ();
dialog . dismiss ();
}
}). show ();
Los parámetros del constructor son
SimpleSearchDialogCompat ( Context context , String title , String searchHint ,
@ Nullable Filter filter , ArrayList < T > items ,
SearchResultListener < T > searchResultListener )
Simplemente use setLoading(true)
para mostrarlo y setLoading(false)
para ocultarlo en una instancia de SimpleSearchDialogCompat.
Si desea cambiar los colores predeterminados, simplemente anule estos colores en su colors.xml
o donde quiera.
< color name = " searchDialogResultColor " />
< color name = " searchDialogResultHighlightColor " />
Utilicé este diseño para un diálogo de búsqueda simple, pero puedes usar cualquier otra cosa. Por supuesto, su diseño debe tener estas dos vistas:
Puede utilizar sus diseños, adaptadores y opciones de búsqueda personalizados creando una clase que herede BaseSearchDialogCompat. Eche un vistazo a SimpleSearchDialogCompat para ver un ejemplo de cómo se puede hacer. Debe implementar los métodos BaseSearchDialogCompat:
// handle your view with this one
protected abstract void getView ( View view );
// Id of your custom layout
@ LayoutRes protected abstract int getLayoutResId ();
// Id of the search edittext you used in your custom layout
@ IdRes protected abstract int getSearchBoxId ();
// Id of the recyclerview you used in your custom layout
@ IdRes protected abstract int getRecyclerViewId ();
Puede utilizar sus filtros personalizados para la búsqueda de texto. El que se utiliza en SimpleSearchDialogCompat es SimpleSearchFilter. Verifica la clave de búsqueda y si un elemento y la clave tenían parcialmente las mismas letras, agregará ese elemento a los resultados y también si CheckLCS se configuró en verdadero, verificará si la cantidad de letras coincidentes era mayor que el AccuracyPercentage dado. El elemento se agregará a los resultados.
el que se usa en SimpleSearchDialogCompat es muy simple a pesar de ser demasiado largo. la funcionalidad principal está en el método inicializeViews. puedes crear tus adaptadores personalizados y usarlos en lugar de este
Tiene dos métodos que puede utilizar para resaltar los resultados.
/*
* Returns a SpannableString with
* highlighted LCS(Longest Common Subsequence)
* of two strings with the givven color
*/
SpannableStringBuilder highlightLCS ( String text1 , String text2 , int highlightColor );
// Returns the LCS(Longest Common Subsequence) of two strings
String lcs ( String text1 , String text2 )
1.2.4 - Added an option to SimpleSearchDialogCompat so that the dialog cancellation on touching outside the dialog can be customized.
1.2.3 - Changed minSdkVersion to 14. Added getter for the title textview of simple search dialog. Improved results sorting.
1.2.2: Gradle tools version and dependencies were updated.
1.2.1: Added an option for changing text color and highlight color of default adapter.
1.2 - Added getter for views in simple search dialog and an option to turn off the auto filtering on search edittext.
1.1.1: Fixes drawable overriding issue.
1.1 - Added loading feature.