Una biblioteca de Android diseñada para simplificar el proceso de implementación de funciones relacionadas con la búsqueda.
mavenCentral()
a su archivo build.gradle
de nivel superior. buildscript {
// ...
repositories {
// ...
mavenCentral()
}
// ...
}
build.gradle
a nivel de módulo. dependencies {
implementation " com.paulrybitskyi.persistentsearchview:persistentsearchview:1.1.5 "
}
targetSdk
es 30 y desea utilizar la función de búsqueda por voz, agregue estas líneas al AndroidManifest.xml
de su aplicación: < manifest ...>
//...
< queries >
< intent >
< action android : name = " android.speech.RecognitionService " />
</ intent >
</ queries >
//...
</ manifest >
La implementación de un PersistentSearchView con funcionalidad básica implica 2 pasos principales: declarar un widget dentro del archivo XML de su elección y configurarlo en una de las clases de Java/Kotlin.
Implementemos un PersistentSearchView con funcionalidad básica siguiendo los pasos enumerados anteriormente:
Declarar un widget dentro del archivo XML.
<? xml version = " 1.0 " encoding = " utf-8 " ?>
< RelativeLayout
xmlns : android = " http://schemas.android.com/apk/res/android "
xmlns : app = " http://schemas.android.com/apk/res-auto "
android : layout_width = " match_parent "
android : layout_height = " match_parent " >
<!-- Other widgets here -->
< com .paulrybitskyi.persistentsearchview.PersistentSearchView
android : id = " @+id/persistentSearchView "
android : layout_width = " match_parent "
android : layout_height = " wrap_content "
android : paddingTop = " 4dp "
android : paddingLeft = " 4dp "
android : paddingStart = " 4dp "
android : paddingRight = " 4dp "
android : paddingEnd = " 4dp " />
</ RelativeLayout >
Configurando el widget en una de las clases de Java/Kotlin.
override fun onCreate ( savedInstanceState : Bundle ? ) {
super .onCreate(savedInstanceState)
setContentView( R .layout.demo_activity_layout)
// ...
with (persistentSearchView) {
setOnLeftBtnClickListener {
// Handle the left button click
}
setOnClearInputBtnClickListener {
// Handle the clear input button click
}
// Setting a delegate for the voice recognition input
setVoiceRecognitionDelegate( VoiceRecognitionDelegate ( this @DemoActivity))
setOnSearchConfirmedListener { searchView, query ->
// Handle a search confirmation. This is the place where you'd
// want to perform a search against your data provider.
}
// Disabling the suggestions since they are unused in
// the simple implementation
setSuggestionsDisabled( true )
}
}
// ...
override fun onActivityResult ( requestCode : Int , resultCode : Int , data : Intent ? ) {
super .onActivityResult(requestCode, resultCode, data)
// Calling the voice recognition delegate to properly handle voice input results
VoiceRecognitionDelegate .handleResult(persistentSearchView, requestCode, resultCode, data)
}
@ Override
protected void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . demo_activity_layout );
//...
persistentSearchView . setOnLeftBtnClickListener ( new OnClickListener () {
@ Override
public void onClick ( View view ) {
// Handle the left button click
}
});
persistentSearchView . setOnClearInputBtnClickListener ( new OnClickListener () {
@ Override
public void onClick ( View view ) {
// Handle the clear input button click
}
});
// Setting a delegate for the voice recognition input
persistentSearchView . setVoiceRecognitionDelegate ( new VoiceRecognitionDelegate ( this ));
persistentSearchView . setOnSearchConfirmedListener ( new OnSearchConfirmedListener () {
@ Override
public void onSearchConfirmed ( PersistentSearchView searchView , String query ) {
// Handle a search confirmation. This is the place where you'd
// want to perform a search against your data provider.
}
});
// Disabling the suggestions since they are unused in
// the simple implementation
persistentSearchView . setSuggestionsDisabled ();
}
//...
@ Override
protected fun onActivityResult ( int requestCode , int resultCode , Intent data ) {
super . onActivityResult ( requestCode , resultCode , data );
// Calling the voice recognition delegate to properly handle voice input results
VoiceRecognitionDelegate . handleResult ( persistentSearchView , requestCode , resultCode , data );
}
La implementación de PersistentSearchView con sugerencias recientes es prácticamente la misma que la implementación básica con una excepción: la configuración de la vista.
En esta implementación, deberá proporcionar un poco más de configuración para el widget a fin de mostrar sugerencias recientes al usuario, como proporcionar implementación para un par de oyentes, así como obtener sugerencias de su proveedor de datos y configurarlas para la búsqueda. vista.
Por ejemplo, aquí está la configuración del widget con la funcionalidad de sugerencias recientes:
@ Override
protected void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . demo_activity_layout );
//...
persistentSearchView . setOnLeftBtnClickListener ( new OnClickListener () {
@ Override
public void onClick ( View view ) {
// Handle the left button click
}
});
persistentSearchView . setOnClearInputBtnClickListener ( new OnClickListener () {
@ Override
public void onClick ( View view ) {
// Handle the clear input button click
}
});
// Setting a delegate for the voice recognition input
persistentSearchView . setVoiceRecognitionDelegate ( new VoiceRecognitionDelegate ( this ));
persistentSearchView . setOnSearchConfirmedListener ( new OnSearchConfirmedListener () {
@ Override
public void onSearchConfirmed ( PersistentSearchView searchView , String query ) {
// Handle a search confirmation. This is the place where you'd
// want to save a new query and perform a search against your
// data provider.
}
});
persistentSearchView . setOnSearchQueryChangeListener ( new OnSearchQueryChangeListener () {
@ Override
public void onSearchQueryChanged ( PersistentSearchView searchView , String oldQuery , String newQuery ) {
// Handle a search query change. This is the place where you'd
// want load new suggestions based on the newQuery parameter.
}
});
persistentSearchView . setOnSuggestionChangeListener ( new OnSuggestionChangeListener () {
@ Override
public void onSuggestionPicked ( SuggestionItem suggestion ) {
// Handle a suggestion pick event. This is the place where you'd
// want to perform a search against your data provider.
}
@ Override
public void onSuggestionRemoved ( SuggestionItem suggestion ) {
// Handle a suggestion remove event. This is the place where
// you'd want to remove the suggestion from your data provider.
}
});
}
//...
@ Override
public void onResume () {
super . onResume ();
List < String > searchQueries = null ;
// Fetching the search queries from the data provider
if ( persistentSearchView . isInputQueryEmpty ) {
searchQueries = mDataProvider . getInitialSearchQueries ();
} else {
searchQueries = mDataProvider . getSuggestionsForQuery ( persistentSearchView . inputQuery );
}
// Converting them to recent suggestions and setting them to the widget
persistentSearchView . setSuggestions ( SuggestionCreationUtil . asRecentSearchSuggestions ( searchQueries ), false );
}
//...
@ Override
protected fun onActivityResult ( int requestCode , int resultCode , Intent data ) {
super . onActivityResult ( requestCode , resultCode , data );
// Calling the voice recognition delegate to properly handle voice input results
VoiceRecognitionDelegate . handleResult ( persistentSearchView , requestCode , resultCode , data );
}
override fun onCreate ( savedInstanceState : Bundle ? ) {
super .onCreate(savedInstanceState)
setContentView( R .layout.demo_activity_layout)
// ...
with (persistentSearchView) {
setOnLeftBtnClickListener {
// Handle the left button click
}
setOnClearInputBtnClickListener {
// Handle the clear input button click
}
// Setting a delegate for the voice recognition input
setVoiceRecognitionDelegate( VoiceRecognitionDelegate ( this @DemoActivity))
setOnSearchConfirmedListener { searchView, query ->
// Handle a search confirmation. This is the place where you'd
// want to save a new query and perform a search against your
// data provider.
}
setOnSearchQueryChangeListener { searchView, oldQuery, newQuery ->
// Handle a search query change. This is the place where you'd
// want load new suggestions based on the newQuery parameter.
}
setOnSuggestionChangeListener( object : OnSuggestionChangeListener {
override fun onSuggestionPicked ( suggestion : SuggestionItem ) {
// Handle a suggestion pick event. This is the place where you'd
// want to perform a search against your data provider.
}
override fun onSuggestionRemoved ( suggestion : SuggestionItem ) {
// Handle a suggestion remove event. This is the place where
// you'd want to remove the suggestion from your data provider.
}
})
}
}
// ...
override fun onResume () {
super .onResume()
// Fetching the search queries from the data provider
val searchQueries = if (persistentSearchView.isInputQueryEmpty) {
mDataProvider.getInitialSearchQueries()
} else {
mDataProvider.getSuggestionsForQuery(persistentSearchView.inputQuery)
}
// Converting them to recent suggestions and setting them to the widget
persistentSearchView.setSuggestions( SuggestionCreationUtil .asRecentSearchSuggestions(searchQueries), false )
}
// ...
override fun onActivityResult ( requestCode : Int , resultCode : Int , data : Intent ? ) {
super .onActivityResult(requestCode, resultCode, data)
// Calling the voice recognition delegate to properly handle voice input results
VoiceRecognitionDelegate .handleResult(persistentSearchView, requestCode, resultCode, data)
}
La implementación de PersistentSearchView con sugerencias regulares es idéntica a la implementación básica de sugerencias recientes con una excepción: el método de creación de sugerencias asRecentSearchSuggestions(searchQueries) debe reemplazarse con asRegularSearchSuggestions(searchQueries).
Vea la aplicación de muestra.
La diferencia entre las sugerencias recientes y las habituales es que un usuario puede eliminar las sugerencias recientes de la lista, mientras que las sugerencias habituales no se pueden eliminar (no hay un botón de eliminación en las sugerencias habituales).
Por ejemplo, aquí hay capturas de pantalla de sugerencias recientes en comparación con las habituales:
Reciente | Regular |
Consulte el archivo CONTRIBUTING.md.
Búho |
¿Estás utilizando PersistentSearchView en tu aplicación y quieres que aparezca aquí? Envíeme un correo electrónico a [email protected].
PersistentSearchView tiene la licencia Apache 2.0.