Uma biblioteca Android projetada para simplificar o processo de implementação de funcionalidades relacionadas à pesquisa.
mavenCentral()
ao seu arquivo build.gradle
de nível superior. buildscript {
// ...
repositories {
// ...
mavenCentral()
}
// ...
}
build.gradle
no nível do módulo. dependencies {
implementation " com.paulrybitskyi.persistentsearchview:persistentsearchview:1.1.5 "
}
targetSdk
for 30 e você quiser usar o recurso de pesquisa por voz, adicione estas linhas ao AndroidManifest.xml
do seu aplicativo: < manifest ...>
//...
< queries >
< intent >
< action android : name = " android.speech.RecognitionService " />
</ intent >
</ queries >
//...
</ manifest >
A implementação de um PersistentSearchView com funcionalidade básica envolve 2 etapas principais - declarar um widget dentro do arquivo XML de sua escolha e configurá-lo em uma das classes Java/Kotlin.
Vamos implementar um PersistentSearchView com funcionalidade básica seguindo as etapas listadas acima:
Declarando um widget dentro do arquivo 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 o widget em uma das classes 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 );
}
A implementação de um PersistentSearchView com sugestões recentes é praticamente igual à implementação básica, com uma exceção: a configuração da visualização.
Nesta implementação você precisará fornecer um pouco mais de configuração para o widget para mostrar sugestões recentes ao usuário, como fornecer implementação para alguns ouvintes, bem como buscar sugestões do seu provedor de dados e configurá-las para a pesquisa visualizar.
Por exemplo, aqui está a configuração do widget com funcionalidade de sugestões recentes:
@ 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)
}
A implementação de um PersistentSearchView com sugestões regulares é idêntica à implementação de sugestões recentes básicas com uma exceção: o método de criação de sugestões asRecentSearchSuggestions(searchQueries) deve ser substituído por asRegularSearchSuggestions(searchQueries).
Consulte o aplicativo de exemplo.
A diferença entre sugestões recentes e regulares é que um usuário pode remover sugestões recentes da lista, enquanto sugestões regulares não podem ser removidas (não há botão de remoção nas sugestões regulares).
Por exemplo, aqui estão capturas de tela de sugestões recentes em comparação com as regulares:
Recente | Regular |
Consulte o arquivo CONTRIBUTING.md.
Corujão |
Usando PersistentSearchView em seu aplicativo e deseja que ele seja listado aqui? Envie-me um e-mail para [email protected]!
PersistentSearchView está licenciado sob a licença Apache 2.0.