추천 검색어 요청 UI 뷰 생성기
추천 검색어 UI 뷰를 가져오려면 다음 단계에 따라 먼저 생성기를 가져와야 합니다.
- 타겟
Activity
클래스가GetSearchSuggestionsViewGeneratorCallback
인터페이스를 구현하거나 익명의 내부 클래스를 사용하도록 합니다. GetSearchSuggestionsViewGeneratorCallback
인터페이스의onSuccess(SearchSuggestionsViewGenerator)
및onError(String)
메서드를 재정의합니다.- 검색 컨텍스트 목록으로
GetSearchSuggestionsViewOptions
클래스 인스턴스를 만듭니다. (선택사항) 이 객체는 검색 추천 UI의 모양을 맞춤설정하는 몇 가지 옵션을 제공하는SearchSuggestionsViewOptions
객체도 사용합니다. SearchInAppsService
의getSearchSuggestionsView(GetSearchSuggestionsViewOptions, GetSearchSuggestionsViewGeneratorCallback)
함수를 호출합니다.- UI 생성기를 가져온 후에는 ViewModel에 저장하여 활동을 다시 만들어야 할 때 (예: 앱이 실행되는 동안 구성이 변경된 경우) 생성기를 다시 요청하지 않아도 되도록 할 수 있습니다.
샘플 코드
자바
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)
...
}
}
위치 기반 검색 추천 요청
getSearchSuggestionsView
진입점은 위치 기반 추천 검색어도 지원합니다. 다음 단계에 따라 LocationContext
객체 목록으로 GetSearchSuggestionsViewOptions
객체를 빌드합니다. 그런 다음 이전 섹션의 단계에 따라 GetSearchSuggestionsViewOptions
를 getSearchSuggestionsView
함수에 전달합니다.
- (필수)
GeographicalRestrictions
객체로LocationContext
객체를 빌드합니다.GeographicalRestrictions
객체는 지역 중심의 위도와 경도, 지역의 반경이 포함된CircularArea
객체를 사용합니다. - (선택사항)
TimeSegment
객체로TimeRestrictions
객체를 빌드합니다.TimeSegment
객체는 ISO 8601 형식으로 시간 세그먼트를 나타내는 문자열을 사용합니다. - (선택사항) 요청된 지리 유형으로
GeoTypeRestrictions
객체를 빌드합니다. 제공된 유형은 서비스에서 반환된 결과의 순위 및 필터링을 조정하는 데 사용됩니다. 지원되는 값은 '음식점', '카페', '바', '공원', '동물원', '박물관', 'attraction', 'atm', 'bank', 'hair_salon', 'real_estate_agency', 'bicycle_sharing_location', 'car_rental_agency', 'shopping_sharing_store', 'hotel.groycenter', '
샘플 코드
자바
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)
...
추천 검색어 UI 뷰 추가
getSearchSuggestionsView
의 경우 최종 출력은 SearchSuggestionsViewGenerator
객체입니다. 이 객체의 populateView(Context)
함수를 사용하여 UI 뷰를 생성하고 updateView(View)
를 사용하여 기존 뷰를 업데이트할 수 있습니다 (특히 Jetpack Compose 앱의 경우).
Jetpack Compose 앱의 경우 AndroidView를 사용하여 생성된 기존 뷰를 사용해야 합니다.
샘플 코드
자바
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) },
)
}
}
}