Đề xuất tìm kiếm

Trình tạo thành phần hiển thị giao diện người dùng đề xuất tìm kiếm

Để có chế độ xem giao diện người dùng gợi ý tìm kiếm, trước tiên, bạn nên lấy trình tạo của chế độ xem đó theo các bước sau:

  1. Cho phép lớp Activity mục tiêu triển khai giao diện GetSearchSuggestionsViewGeneratorCallback hoặc sử dụng lớp bên trong ẩn danh.
  2. Ghi đè các phương thức onSuccess(SearchSuggestionsViewGenerator)onError(String) của giao diện GetSearchSuggestionsViewGeneratorCallback.
  3. Tạo thực thể lớp GetSearchSuggestionsViewOptions với danh sách các ngữ cảnh tìm kiếm. (Không bắt buộc) Đối tượng này cũng lấy một đối tượng SearchSuggestionsViewOptions cung cấp một số tuỳ chọn để tuỳ chỉnh giao diện người dùng của nội dung đề xuất tìm kiếm.
  4. Gọi hàm getSearchSuggestionsView(GetSearchSuggestionsViewOptions, GetSearchSuggestionsViewGeneratorCallback) của SearchInAppsService.
  5. Sau khi nhận được trình tạo giao diện người dùng, bạn có thể cân nhắc lưu trữ trình tạo đó trong ViewModel để không cần yêu cầu lại trình tạo khi hoạt động cần tạo lại (chẳng hạn như khi cấu hình đã thay đổi trong khi ứng dụng đang chạy).

Mã mẫu

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)
  ...
 }
}

Yêu cầu đề xuất tìm kiếm dựa trên vị trí

Điểm truy cập getSearchSuggestionsView cũng hỗ trợ các đề xuất tìm kiếm dựa trên vị trí. Tạo một đối tượng GetSearchSuggestionsViewOptions có danh sách các đối tượng LocationContext theo các bước sau. Sau đó, hãy truyền GetSearchSuggestionsViewOptions vào hàm getSearchSuggestionsView theo các bước trong phần trước.

  1. (Bắt buộc) Tạo đối tượng LocationContext bằng đối tượng GeographicalRestrictions. Đối tượng GeographicalRestrictions lấy một đối tượng CircularArea chứa vĩ độ và kinh độ của tâm khu vực và bán kính của khu vực.
  2. (Không bắt buộc) Tạo đối tượng TimeRestrictions bằng đối tượng TimeSegment. Đối tượng TimeSegment nhận một chuỗi đại diện cho phân đoạn thời gian ở định dạng ISO 8601.
  3. (Không bắt buộc) Tạo đối tượng GeoTypeRestrictions bằng các loại địa lý được yêu cầu. Các loại được cung cấp được dùng để điều chỉnh thứ hạng và lọc kết quả do dịch vụ trả về. Các giá trị được hỗ trợ là: "restaurant", "cafe", "bar", "park", "zoo", "museum", "attraction", "atm", "bank", "hair_salon", "real_estate_agency", "bicycle_sharing_location", "car_rental_agency", "shopping_center", "grocery_store" và "hotel".

Mã mẫu

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)
...

Thêm thành phần hiển thị giao diện người dùng đề xuất tìm kiếm

Đối với getSearchSuggestionsView, kết quả cuối cùng là một đối tượng SearchSuggestionsViewGenerator. Bạn có thể sử dụng hàm populateView(Context) của đối tượng này để tạo thành phần hiển thị giao diện người dùng và updateView(View) để cập nhật thành phần hiển thị hiện có (đặc biệt là đối với các ứng dụng Jetpack Compose).

Đối với các ứng dụng Jetpack Compose, bạn nên sử dụng AndroidView để sử dụng khung hiển thị cổ điển đã tạo.

Mã mẫu

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) },
      )
    }
  }
}

Tiếp theo: Hiển thị kết quả tìm kiếm