Solicita el generador de vistas de la IU de sugerencias de búsqueda
Para obtener la vista de la IU de las sugerencias de búsqueda, primero debes obtener su generador siguiendo estos pasos:
- Permite que tu clase
Activity
de destino implemente la interfazGetSearchSuggestionsViewGeneratorCallback
o usa la clase interna anónima. - Anula los métodos
onSuccess(SearchSuggestionsViewGenerator)
yonError(String)
de la interfazGetSearchSuggestionsViewGeneratorCallback
. - Construye la instancia de la clase
GetSearchSuggestionsViewOptions
con una lista de contextos de búsqueda. (Opcional) Este objeto también toma un objetoSearchSuggestionsViewOptions
que proporciona algunas opciones para personalizar el aspecto de la IU de las sugerencias de búsqueda. - Llama a la función
getSearchSuggestionsView(GetSearchSuggestionsViewOptions, GetSearchSuggestionsViewGeneratorCallback)
deSearchInAppsService
. - Después de obtener el generador de IU, puedes considerar almacenarlo en un ViewModel para que no tengas que solicitar el generador de nuevo cuando la actividad deba volver a crearse (por ejemplo, cuando cambia la configuración mientras se ejecuta la app).
Código de muestra
Java
package ...;
...
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewGeneratorCallback;
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewOptions;
import com.google.android.libraries.searchinapps.SearchInAppsService;
import com.google.android.libraries.searchinapps.SearchSuggestionsViewGenerator;
import java.util.Arrays;
import java.util.List;
...
public class MainActivity extends AppCompatActivity implements GetSearchSuggestionsViewGeneratorCallback {
private SearchInAppsService service;
@Override
public void onSuccess(SearchSuggestionsViewGenerator generator) {
...
}
@Override
public void onError(String errorMessage) {
...
}
@Override
protected void onCreate(Bundle savedInstanceState) {
...
service = SearchInAppsService.create(this);
// Right now only the first element of this list will be used.
List<String> searchContext = Arrays.asList(new String[]{"This is a test query, for example."});
// Uses the default SearchSuggestionsViewOptions.
service.getSearchSuggestionsView(
new GetSearchSuggestionsViewOptions().setTextContext(searchContext),this);
...
}
@Override
public void onDestroy() {
service.shutDown();
super.onDestroy();
}
}
Jetpack Compose
package ...
...
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.LocalContext
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewGeneratorCallback
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewOptions
import com.google.android.libraries.searchinapps.SearchInAppsService
import com.google.android.libraries.searchinapps.SearchSuggestionsViewGenerator
...
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
SearchSuggestionsUI()
}
}
@Composable
fun SearchSuggestionsUI() {
...
var service by remember {
mutableStateOf<SearchInAppsService?>(
SearchInAppsService.create(LocalContext.current))
}
DisposableEffect(Unit) { onDispose { service?.shutDown() } }
val callback =
object : GetSearchSuggestionsViewGeneratorCallback {
override fun onSuccess(generator: SearchSuggestionsViewGenerator) {
...
}
override fun onError(errorMessage: String) {
...
}
}
var searchContexts: List<String> = listOf<String>("Query")
// Uses the default SearchSuggestionsViewOptions.
var options: GetSearchSuggestionsViewOptions =
GetSearchSuggestionsViewOptions()
.setTextContext(searchContexts)
service?.getSearchSuggestionsView(options, callback)
...
}
}
Cómo solicitar sugerencias de búsqueda basadas en la ubicación
El punto de entrada getSearchSuggestionsView
también admite sugerencias de búsqueda basadas en la ubicación. Sigue estos pasos para compilar un objeto GetSearchSuggestionsViewOptions
con una lista de objetos LocationContext
. Luego, pasa el
GetSearchSuggestionsViewOptions
a la función getSearchSuggestionsView
,
siguiendo los pasos de la sección anterior.
- (Obligatorio) Compila el objeto
LocationContext
con el objetoGeographicalRestrictions
. El objetoGeographicalRestrictions
toma un objetoCircularArea
que contiene la latitud y longitud del centro del área y el radio del área. - (Opcional) Compila el objeto
TimeRestrictions
con el objetoTimeSegment
. El objetoTimeSegment
toma una cadena que representa el segmento de tiempo en formato ISO 8601. - Compila el objeto
GeoTypeRestrictions
con los tipos geográficos solicitados (opcional). Los tipos proporcionados se usan para ajustar la clasificación y el filtrado de los resultados que muestra el servicio. Los valores admitidos son: "restaurant", "cafe", "bar", "park", "zoo", "museum", "attraction", "atm", "bank", "hair_salon", "real_estate_agency", "bicycle_sharing_location", "car_rental_agency", "shopping_center", "grocery_store" y "hotel".
Código de muestra
Java
package ...;
...
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewGeneratorCallback;
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewOptions;
import com.google.android.libraries.searchinapps.LocationContext;
import com.google.android.libraries.searchinapps.LocationContext.CircularArea;
import com.google.android.libraries.searchinapps.LocationContext.GeoTypeRestrictions;
import com.google.android.libraries.searchinapps.LocationContext.GeographicalRestrictions;
import com.google.android.libraries.searchinapps.LocationContext.LatLng;
import com.google.android.libraries.searchinapps.LocationContext.TimeRestrictions;
import com.google.android.libraries.searchinapps.LocationContext.TimeSegment;
import com.google.android.libraries.searchinapps.SearchInAppsService;
import com.google.android.libraries.searchinapps.SearchSuggestionsViewGenerator;
...
LocationContext locationContext = new LocationContext(
new GeographicalRestrictions(
new CircularArea(
new LatLng(
40.7414728,
-74.0059622),
1000)))
// Optional. If set, the returned suggestions are categories of which
// there are several businesses in the requested area that are open at
// the given time.
.setTimeRestrictions(
new TimeRestrictions(
new TimeSegment("2024-05-18T19:20:30.45+01:00")))
// Optional. If set, the returned suggestions are subset of the
// requested categories.
.setGeoTypeRestrictions(
new GeoTypeRestrictions("restaurant", "parks"));
// Uses the default SearchSuggestionsViewOptions.
service = SearchInAppsService.create(this);
// Uses the default SearchSuggestionsViewOptions.
service.getSearchSuggestionsView(
new GetSearchSuggestionsViewOptions().setLocationContext(Arrays.asList(locationContext)), this);
Jetpack Compose
package ...
...
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewGeneratorCallback
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewOptions
import com.google.android.libraries.searchinapps.LocationContext
import com.google.android.libraries.searchinapps.LocationContext.CircularArea
import com.google.android.libraries.searchinapps.LocationContext.GeoTypeRestrictions
import com.google.android.libraries.searchinapps.LocationContext.GeographicalRestrictions
import com.google.android.libraries.searchinapps.LocationContext.LatLng
import com.google.android.libraries.searchinapps.LocationContext.TimeRestrictions
import com.google.android.libraries.searchinapps.LocationContext.TimeSegment
import com.google.android.libraries.searchinapps.SearchInAppsService
import com.google.android.libraries.searchinapps.SearchSuggestionsViewGenerator
...
var locationContext: LocationContext = LocationContext(
GeographicalRestrictions(
CircularArea(
LatLng(40.7414728, -74.0059622),
1000)))
// Optional. If set, there are several businesses in the requested area that
// are open at the given time.
.setTimeRestrictions(
TimeRestrictions(
TimeSegment("2024-05-18T19:20:30.45+01:00")))
// Optional. If set, the returned suggestions are subset of the requested
// categories.
.setGeoTypeRestrictions(
GeoTypeRestrictions("restaurant", "parks"))
// Uses the default SearchSuggestionsViewOptions.
var options: GetSearchSuggestionsViewOptions =
GetSearchSuggestionsViewOptions()
.setLocationContext(listOf<LocationContext>(locationContext))
service.getSearchSuggestionsView(options, callback)
...
Cómo agregar la vista de la IU de sugerencias de búsqueda
Para getSearchSuggestionsView
, el resultado final es un objeto SearchSuggestionsViewGenerator
. Puedes usar la función populateView(Context)
de este objeto para generar la vista de la IU y updateView(View)
para actualizar la vista existente (especialmente para apps de Jetpack Compose).
En el caso de las apps de Jetpack Compose, debes usar AndroidView para consumir la vista clásica generada.
Código de muestra
Java
package ...;
...
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewGeneratorCallback;
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewOptions;
import com.google.android.libraries.searchinapps.SearchInAppsService;
import com.google.android.libraries.searchinapps.SearchSuggestionsViewGenerator;
import java.util.Arrays;
import java.util.List;
...
public class MainActivity extends AppCompatActivity implements GetSearchSuggestionsViewGeneratorCallback {
private SearchInAppsService service;
@Override
public void onSuccess(SearchSuggestionsViewGenerator generator) {
ViewGroup container = findViewById(R.id.[container_id]);
container.removeAllViews();
container.addView(generator.populateView(this));
}
@Override
public void onError(String errorMessage) {
...
}
@Override
protected void onCreate(Bundle savedInstanceState) {
...
service = SearchInAppsService.create(this);
List<String> searchContext = Arrays.asList(new String[]{"Query"});
// Uses the default SearchSuggestionsViewOptions.
service.getSearchSuggestionsView(
new GetSearchSuggestionsViewOptions().setTextContext(searchContext),this);
...
}
@Override
public void onDestroy() {
service.shutDown();
super.onDestroy();
}
}
Jetpack Compose
package ...
...
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewGeneratorCallback
import com.google.android.libraries.searchinapps.GetSearchSuggestionsViewOptions
import com.google.android.libraries.searchinapps.SearchInAppsService
import com.google.android.libraries.searchinapps.SearchSuggestionsViewGenerator
...
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { SearchSuggestionsUI() }
}
@Composable
fun SearchSuggestionsUI() {
...
var service by remember {
mutableStateOf<SearchInAppsService?>(
SearchInAppsService.create(LocalContext.current))
}
var viewGenerator = mutableStateOf<SearchSuggestionsViewGenerator?>(null)
DisposableEffect(Unit) { onDispose { service?.shutDown() } }
val callback =
object : GetSearchSuggestionsViewGeneratorCallback {
override fun onSuccess(generator: SearchSuggestionsViewGenerator) {
viewGenerator.value = generator
}
override fun onError(errorMessage: String) {}
}
var searchContexts: List<String> = listOf<String>("Query")
// Uses the default SearchSuggestionsViewOptions.
var options: GetSearchSuggestionsViewOptions =
GetSearchSuggestionsViewOptions().setTextContext(searchContexts)
service?.getSearchSuggestionsView(options, callback)
ChipGroupUI(viewGenerator)
...
}
@Composable
fun ChipGroupUI(viewGenerator: MutableState<SearchSuggestionsViewGenerator?>) {
viewGenerator.value?.let { viewGenerator ->
var context = LocalContext.current
AndroidView(
factory = { context -> viewGenerator.populateView(context) },
update = { view -> viewGenerator.updateView(view, context) },
)
}
}
}