Jitendra Prajapati
Jitendra Prajapati

Reputation: 1163

JetPack Compose AndroidView Pass to function

I am trying to convert below code in Jetpack compose UI,

    searchResultsView = findViewById<SearchResultsView>.(R.id.search_results_view).apply {
        initialize(
            SearchResultsView.Configuration(CommonSearchViewConfiguration(DistanceUnitType.IMPERIAL))
        )
        isVisible = false
    }


    searchEngineUiAdapter = SearchEngineUiAdapter(
        view = searchResultsView,
        searchEngine = searchEngine,
        offlineSearchEngine = offlineSearchEngine,
    )

I Need to pass searchResultView in our function SearchEngineUiAdapter,

I Stuck here , because searchView is now AndroidView and it as a Compose component, so we can not passed to a function. I don’t know inject this searchResultsView into a function

below is final code

AndroidView(
        factory = { context ->
            SearchResultsView(context).apply {
                initialize(
                    SearchResultsView.Configuration(
                        CommonSearchViewConfiguration(
                            DistanceUnitType.IMPERIAL
                        )
                    )
                )
            }
        },
        modifier = Modifier
            .fillMaxWidth()
            .background(color = Color.Blue)

Upvotes: 0

Views: 966

Answers (2)

Pavel
Pavel

Reputation: 75

I am not sure, but I have the same problem, I have to send view into another class from the same library.

I tried this:

val context = LocalContext.current
val view: View = remember(context) { TextView(context) }

AndroidView(
    modifier = Modifier.fillMaxSize(),
    factory = { ctx ->
        if (ctx == context) view
        else throw IllegalStateException("Problem with context")
    },
)

LaunchEffect(view) {  
    sendViewRef(view)
}

Upvotes: 0

RufusInZen
RufusInZen

Reputation: 2189

In Jetpack Compose, you provide the data to the composable function to display, not the other way around. You should initialize and get your search results in a viewModel outside and then pass that data for display to the search results composable.

val searchResults = searchViewModel.getSearchResults()
AndroidView(
    factory = { context ->
        SearchResultsView(searchResults)
        }
    },
    modifier = Modifier
        .fillMaxWidth()
        .background(color = Color.Blue)

Upvotes: 0

Related Questions