콘텐츠 검색

검색 콘텐츠 UI 뷰 생성기 요청

SDK에 검색 콘텐츠 UI 뷰를 반환하는 지원이 추가되었습니다. Search Content는 여러 유형의 콘텐츠 기능을 나타내는 일반적인 용어입니다. 각 유형의 콘텐츠 기능을 각각 요청하는 방법은 다음 섹션을 확인하세요.

검색 반복

검색 반복의 UI 뷰를 가져오려면 먼저 다음 단계에 따라 검색 콘텐츠 생성기를 가져와야 합니다.

  1. GetSearchContentViewGeneratorCallback 클래스의 onSuccess 메서드와 onError 메서드를 재정의합니다.
  2. GetSearchContentViewGeneratorCallback 클래스의 인스턴스를 만듭니다.
  3. GetSearchContentViewOptions 클래스 인스턴스를 생성하고 setSearchRepeatContext 메서드를 호출하여 검색 반복 컨텍스트를 설정합니다. (선택사항) 이 객체는 UI의 모양을 맞춤설정하는 몇 가지 옵션을 제공하는 SearchContentViewOptions 객체도 사용합니다.
  4. SearchInAppsServicegetSearchContentView(GetSearchContentViewOptions, GetSearchContentViewGeneratorCallback) 함수를 호출합니다.
  5. UI 생성기를 가져온 후에는 ViewModel에 저장하여 활동을 다시 만들어야 할 때 (예: 앱 실행 중에 구성이 변경된 경우) 생성기를 다시 요청하지 않아도 됩니다.

샘플 코드

자바

package ...;

...
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.libraries.searchinapps.GetSearchContentViewGeneratorCallback;
import com.google.android.libraries.searchinapps.GetSearchContentViewOptions;
import com.google.android.libraries.searchinapps.SearchInAppsService;
import com.google.android.libraries.searchinapps.SearchContentViewGenerator;
...

public class MainActivity extends AppCompatActivity {
  private SearchInAppsService service;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    ...
    service = SearchInAppsService.create(this);
    GetSearchContentViewGeneratorCallback searchContentCallback =
      new GetSearchContentViewGeneratorCallback() {
        @Override
        public void onSuccess(SearchContentViewGenerator generator) {
          ...
        }

        @Override
        public void onError(String errorMessage) {
          ...
        }
      };

    // Uses the default SearchContentViewOptions.
    service.getSearchContentView(
      new GetSearchContentViewOptions().setSearchRepeatContext(
          "sample search repeat"), searchContentCallback);
    ...
  }

  @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.GetSearchContentViewGeneratorCallback
import com.google.android.libraries.searchinapps.GetSearchContentViewOptions
import com.google.android.libraries.searchinapps.SearchInAppsService
import com.google.android.libraries.searchinapps.SearchContentViewGenerator
...

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      SearchRepeatUI()
    }
  }

  @Composable
  fun SearchRepeatUI() {
    ...
    var service by remember {
      mutableStateOf<SearchInAppsService?>(
        SearchInAppsService.create(LocalContext.current))
    }
    DisposableEffect(Unit) { onDispose { service?.shutDown() } }
    val callback =
            object : GetSearchContentViewGeneratorCallback() {
              override fun onSuccess(generator: SearchContentViewGenerator) {
                ...
              }

              override fun onError(errorMessage: String) {
                ...
              }
            }
    // Uses the default SearchContentViewOptions.
    var options: GetSearchContentViewOptions =
            GetSearchContentViewOptions()
              .setSearchRepeatContext("sample search repeat")
    service?.let { service ->
      service.getSearchContentView(options, callback)
    }
    ...
  }
}

검색 콘텐츠 UI 뷰 추가

getSearchContentView의 경우 최종 출력은 SearchContentViewGenerator 객체입니다. 이 객체의 populateView(Context, int) 함수를 사용하여 UI 뷰를 생성하고 updateView(View, Context)를 사용하여 기존 뷰를 업데이트할 수 있습니다(특히 Jetpack Compose 앱의 경우).

Jetpack Compose 앱의 경우 AndroidView를 사용하여 생성된 기존 뷰를 사용해야 합니다.

샘플 코드

자바

package ...;

...
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.libraries.searchinapps.GetSearchContentViewGeneratorCallback;
import com.google.android.libraries.searchinapps.GetSearchContentViewOptions;
import com.google.android.libraries.searchinapps.SearchInAppsService;
import com.google.android.libraries.searchinapps.SearchContentViewGenerator;
import java.util.Arrays;
import java.util.List;
...

public class MainActivity extends AppCompatActivity {
  private SearchInAppsService service;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    ...
    service = SearchInAppsService.create(this);
    GetSearchContentViewGeneratorCallback searchContentCallback =
      new GetSearchContentViewGeneratorCallback() {
        @Override
        public void onSuccess(SearchContentViewGenerator generator) {
          ViewGroup container = findViewById(R.id.[container_id]);
          container.removeAllViews();
          searchContentBlock = 0;
          // If you don't specify "numberOfBlocksToRequest" in
          // GetSearchContentViewOptions, by default
          // SearchContentViewGenerator.getSearchContentBlockCount() always
          // returns 1.
          while (searchContentBlock <
            generator.getSearchContentBlockCount()) {
              container.addView(
                  generator.populateView(MainActivity.this,
                    searchContentBlock));
              searchContentBlock++;
          }
        }

        @Override
        public void onError(String errorMessage) {
          ...
        }
      };

    // Uses the default SearchContentViewOptions.
    service.getSearchContentView(
      new GetSearchContentViewOptions().setSearchRepeatContext(
        "sample search repeat"), searchContentCallback);
    ...
  }

  @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.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import com.google.android.libraries.searchinapps.GetSearchContentViewGeneratorCallback
import com.google.android.libraries.searchinapps.GetSearchContentViewOptions
import com.google.android.libraries.searchinapps.SearchInAppsService
import com.google.android.libraries.searchinapps.SearchContentViewGenerator
...

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent { SearchRepeatUI() }
  }

  @Composable
  fun SearchRepeatUI() {
    ...
    var service by remember {
      mutableStateOf<SearchInAppsService?>(
        SearchInAppsService.create(LocalContext.current))
    }
    var viewGenerator by remember {
        mutableStateOf<SearchContentViewGenerator?>(null) }
    var searchContentBlockNumber by remember { mutableStateOf(0) }
    DisposableEffect(Unit) { onDispose { service?.shutDown() } }
    val callback =
            object : GetSearchContentViewGeneratorCallback() {
              override fun onSuccess(
                  generator: SearchContentViewGenerator) {
                viewGenerator = generator
                // If you don't specify "numberOfBlocksToRequest" in
                // GetSearchContentViewOptions, by default
                // SearchContentViewGenerator.getSearchContentBlockCount()
                // always returns 1.
                searchContentBlockNumber =
                  generator.getSearchContentBlockCount()
              }

              override fun onError(errorMessage: String) {
                ...
              }
            }
    // Uses the default SearchContentViewOptions.
    var options: GetSearchContentViewOptions =
            GetSearchContentViewOptions()
              .setSearchRepeatContext("sample search repeat")
    service?.getSearchContentView(options, callback)
    SearchRepeatUIComposable(viewGenerator, searchContentBlockNumber)
    ...
}

  @Composable
  fun SearchRepeatUIComposable(viewGenerator: SearchContentViewGenerator?,
  searchContentBlockNumber: Int,) {
    viewContentGenerator?.let { viewContentGenerator ->
      var context = LocalContext.current
      Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
      for (index in 0..searchContentBlockNumber - 1) {
        Row {
          AndroidView(
            factory = { context ->
              viewContentGenerator.populateView(context, index) },
            update = { view ->
              viewContentGenerator.updateView(view, context) },
          )
        }
      }
    }
  }
}

다음: 검색 결과 표시