Getting Started with Imperative UI
On this page
This guide walks you through the few steps needed to start a project with InstantSearch Android. It starts from an empty Android project, and creates a full search experience from scratch.
This search experience includes:
- A list to display search results
- A search box to type your query
- Statistics about the current search
- A facet list for filtering results
Installation
To use Algolia with InstantSearch Android, you need an Algolia account. You can sign up for a new account, or use the following credentials:
- Application ID:
latency
- Search API Key:
3d9875e51fbd20c7754e65422f7ce5e1
- Index name:
bestbuy
These credentials will let you use a preloaded dataset of products appropriate for this guide.
Create a new project and add InstantSearch Android
In Android Studio, create a new Project:
- On the Target screen, select Phone and Tablet
- On the Add an Activity screen, select Empty Activity
In your app’s build.gradle
, add the following dependency:
1
implementation 'com.algolia:instantsearch-android:2.X.X'
Replace 2.X.X
with the latest release.
This guide uses InstantSearch Android with Android Architecture Components, so you also need to add the following dependencies:
1
2
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
implementation "androidx.lifecycle:lifecycle-common:2.2.0"
You also need to add packagingOptions
to the android
block in build.gradle
:
1
2
3
packagingOptions {
exclude 'META-INF/*.kotlin_module'
}
To perform network operations in your application, AndroidManifest.xml
must include the following permissions:
1
<uses-permission android:name="android.permission.INTERNET" />
Implementation
Architecture overview
MainActivity
: This activity controls the fragment currently displayed.MyViewModel
: AViewModel
from Android Architecture Components. The business logic lives here.ProductFragment
: This fragment displays a list of search results in aRecyclerView
, aSearchView
input, and aStats
indicator.FacetFragment
: This fragment displays a list of facets to filter your search results.
Initializing a Searcher
The central part of your search experience is the Searcher
. The Searcher
performs search requests and obtains search results. Most InstantSearch components are connected with the Searcher
.
In this tutorial you will only target one index, so instantiate a SearcherSingleIndex
with the proper credentials.
Go to MyViewModel.kt
file and add the following code:
1
2
3
4
5
6
7
8
9
10
11
class MyViewModel : ViewModel() {
val client = ClientSearch(ApplicationID("latency"), APIKey("1f6fd3a6fb973cb08419fe7d288fa4db"), LogLevel.ALL)
val index = client.initIndex(IndexName("bestbuy_promo"))
val searcher = SearcherSingleIndex(index)
override fun onCleared() {
super.onCleared()
searcher.cancel()
}
}
A ViewModel
is a good place to put your data sources. This way, the data persists during orientation changes and you can share it across multiple fragments.
Displaying your results: Hits
Suppose you want to display search results in a RecyclerView
. To simultaneously provide a good user experience and display thousands of products, you can implement an infinite scrolling mechanism using the Paging Library from Android Architecture Component.
The first step to display your results is to create a LiveData
object, which holds a PagedList
of Product
.
Create the Product
data class which contains a single name
field.
1
2
3
data class Product(
val name: String
)
Create the product_item.xml
file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<com.google.android.material.card.MaterialCardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="?attr/listPreferredItemHeightSmall"
android:layout_marginBottom="0.5dp"
app:cardCornerRadius="0dp"
tools:layout_height="50dp">
<TextView
android:id="@+id/productName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:ellipsize="end"
android:maxLines="1"
android:textAppearance="?attr/textAppearanceBody1"
android:textSize="16sp"
tools:text="@tools:sample/lorem/random" />
</com.google.android.material.card.MaterialCardView>
Create the ProductViewHolder
to bind a Product
item to a RecyclerView.ViewHolder
.
1
2
3
4
5
6
class ProductViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
fun bind(product: Product) {
view.productName.text = product.name
}
}
Create a ProductAdapter
by extending PagedListAdapter
. The ProductAdapter
binds products to the ViewHolder
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class ProductAdapter : PagedListAdapter<Product, ProductViewHolder>(ProductAdapter) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.product_item, parent, false)
return ProductViewHolder(view)
}
override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
val product = getItem(position)
if (product != null) holder.bind(product)
}
companion object : DiffUtil.ItemCallback<Product>() {
override fun areItemsTheSame(
oldItem: Product,
newItem: Product
): Boolean {
return oldItem.name == newItem.name
}
override fun areContentsTheSame(
oldItem: Product,
newItem: Product
): Boolean {
return oldItem == newItem
}
}
}
You can now use the SearcherSingleIndexDataSource.Factory
with your searcher to create a LiveData<PagedList<Product>>
. Do this in your ViewModel
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class MyViewModel : ViewModel() {
// Searcher initialization
// ...
val dataSourceFactory = SearcherSingleIndexDataSource.Factory(searcher) { hit ->
Product(
hit.json.getPrimitive("name").content
)
}
val pagedListConfig = PagedList.Config.Builder().setPageSize(50).build()
val products: LiveData<PagedList<Product>> = LivePagedListBuilder(dataSourceFactory, pagedListConfig).build()
override fun onCleared() {
super.onCleared()
searcher.cancel()
}
}
To keep this example simple, you can create the Product
object manually from the hit’s JSON.
However, for production applications, you can use the kotlinx.serialization
library to transform JSON into your objects.
Now that your ViewModel
has some data, you can create a simple product_fragment.xml
with a Toolbar
and a RecyclerView
to display the products:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_height="?attr/actionBarSize"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/productList"
app:layout_constraintTop_toBottomOf="@id/toolbar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_width="0dp"
android:layout_height="0dp"
tools:listitem="@layout/product_item"/>
</androidx.constraintlayout.widget.ConstraintLayout>
In the ProductFragment
, get a reference of MyViewModel
with a ViewModelProviders
.
Then, observe the LiveData
to update the ProductAdapter
on every new page of products.
Finally, configure the RecyclerView
by setting its adapter and LayoutManager
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class ProductFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.product_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val viewModel = ViewModelProvider(requireActivity())[MyViewModel::class.java]
val adapterProduct = ProductAdapter()
viewModel.products.observe(viewLifecycleOwner, Observer { hits -> adapterProduct.submitList(hits) })
productList.let {
it.itemAnimator = null
it.adapter = adapterProduct
it.layoutManager = LinearLayoutManager(requireContext())
it.autoScrollToStart(adapterProduct)
}
}
}
To display the ProductFragment
, update activity_main.xml
to have a container for the fragments:
1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Update MainActivity
to display ProductFragment
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
showProductFragment()
}
fun showProductFragment() {
supportFragmentManager
.beginTransaction()
.add(R.id.container, ProductFragment())
.commit()
}
}
You have now learned how to display search results in an infinite scrolling RecyclerView
.
Searching your data: SearchBox
To search your data, users need an input field. Any change in this field should trigger a new request, and then update the search results.
To achieve this, use a SearchBoxConnectorPagedList
. This takes a Searcher
and one or multiple LiveData<PagedList<T>>
as arguments.
First, pass your products LiveData
defined before:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class MyViewModel : ViewModel() {
// Searcher initialization
// Hits initialization
// ...
val searchBox = SearchBoxConnectorPagedList(searcher, listOf(products))
val connection = ConnectionHandler()
init {
connection += searchBox
}
override fun onCleared() {
super.onCleared()
searcher.cancel()
connection.clear()
}
}
Most InstantSearch components should be connected and disconnected in accordance to the Android Lifecycle to avoid memory leaks.
A ConnectionHandler
handles a set of Connection
s for you: Each +=
call with a component implementing the Connection
interface will connect it and make it active. Whenever you want to free resources or deactivate a component, call the disconnect
method.
You can now add a SearchView
in your Toolbar
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:clipToPadding="false">
<androidx.appcompat.widget.SearchView
android:id="@+id/searchView"
android:layout_width="0dp"
android:layout_height="0dp"
android:focusable="false"
app:iconifiedByDefault="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/productList"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/toolbar"
tools:listitem="@layout/product_item" />
</androidx.constraintlayout.widget.ConstraintLayout>
Connect the SearchBoxViewAppCompat
to the SearchBoxConnectorPagedList
stored in MyViewModel
using a new ConnectionHandler
that conforms to the ProductFragment
lifecycle:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class ProductFragment : Fragment() {
private val connection = ConnectionHandler()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.product_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val viewModel = ViewModelProviders.of(requireActivity())[MyViewModel::class.java]
// Hits
// ...
val searchBoxView = SearchBoxViewAppCompat(searchView)
connection += viewModel.searchBox.connectView(searchBoxView)
}
override fun onDestroyView() {
super.onDestroyView()
connection.clear()
}
}
You can now build and run your application, and see a basic search experience. The results change with each key stroke.
Displaying metadata: Stats
It’s a good practice to show the number of hits that were returned for a search. You can use the Stats
components to achieve this in a few lines.
Add a StatsConnector
to your MyViewModel
, and connect it with a ConnectionHandler
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class MyViewModel : ViewModel() {
// Searcher initialization
// Hits initialization
// SearchBox initialization
// ...
val stats = StatsConnector(searcher)
val connection = ConnectionHandler()
init {
// SearchBox connection
// ...
connection += stats
}
override fun onCleared() {
super.onCleared()
searcher.cancel()
connection.clear()
}
}
Add a TextView
to your product_fragment.xml
file to display the stats.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:clipToPadding="false">
<androidx.appcompat.widget.SearchView
android:id="@+id/searchView"
android:layout_width="0dp"
android:layout_height="0dp"
android:focusable="false"
app:iconifiedByDefault="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.Toolbar>
<TextView
android:id="@+id/stats"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:padding="16dp"
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/toolbar" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/productList"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/stats"
tools:listitem="@layout/product_item" />
</androidx.constraintlayout.widget.ConstraintLayout>
Finally, connect the StatsConnector
to a StatsTextView
in your ProductFragment
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class ProductFragment : Fragment() {
private val connection = ConnectionHandler()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.product_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val viewModel = ViewModelProviders.of(requireActivity())[MyViewModel::class.java]
// Hits
// SearchBox
// ...
val statsView = StatsTextView(stats)
connection += viewModel.stats.connectView(statsView, StatsPresenterImpl())
}
override fun onDestroyView() {
super.onDestroyView()
connection.clear()
}
}
You can now build and run your application and see your new search experience in action.
Filter your data: FacetList
Filtering search results helps your users find exactly what they want. You can create a FacetList
to filter products by category.
Create a drawable resource ic_check.xml
. This resource displays checked filters.
1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M9,16.17L4.83,12l-1.42,1.41L9,19 21,7l-1.41,-1.41z"/>
</vector>
Create a facet_item.xml
file. This is the layout for a RecyclerView.ViewHolder
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<com.google.android.material.card.MaterialCardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="?attr/listPreferredItemHeightSmall"
android:layout_marginBottom="0.5dp"
app:cardCornerRadius="0dp"
tools:layout_height="50dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="12dp"
android:src="@drawable/ic_check"
android:tint="?attr/colorPrimary"
android:visibility="invisible"
app:layout_constrainedHeight="true"
app:layout_constrainedWidth="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:visibility="visible" />
<TextView
android:id="@+id/facetCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:ellipsize="end"
android:gravity="end"
android:maxLines="1"
android:textAppearance="?attr/textAppearanceBody2"
android:textColor="#818794"
android:textSize="16sp"
android:visibility="gone"
app:layout_constrainedHeight="true"
app:layout_constrainedWidth="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/icon"
app:layout_constraintTop_toTopOf="parent"
tools:text="@tools:sample/lorem"
tools:visibility="visible" />
<TextView
android:id="@+id/facetName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:ellipsize="end"
android:maxLines="1"
android:textAppearance="?attr/textAppearanceBody1"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/facetCount"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="@tools:sample/lorem/random" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>
Implement the FacetListViewHolder
and its Factory
, so that later on it works with a FacetListAdapter
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import com.algolia.search.model.search.Facet
class MyFacetListViewHolder(view: View) : FacetListViewHolder(view) {
override fun bind(facet: Facet, selected: Boolean, onClickListener: View.OnClickListener) {
view.setOnClickListener(onClickListener)
view.facetCount.text = facet.count.toString()
view.facetCount.visibility = View.VISIBLE
view.icon.visibility = if (selected) View.VISIBLE else View.INVISIBLE
view.facetName.text = facet.value
}
object Factory : FacetListViewHolder.Factory {
override fun createViewHolder(parent: ViewGroup): FacetListViewHolder {
return MyFacetListViewHolder(parent.inflate(R.layout.facet_item))
}
}
}
You can use a new component to handle the filtering logic: the FilterState
.
Pass the FilterState
to your FacetListConnector
. The FacetListConnector
needs an Attribute
: you should use category
.
Inject MyFacetListViewHolder.Factory
into your FacetListAdapter
. The FacetListAdapter
is an out of the box RecyclerView.Adapter
for a FacetList
.
Connect the different parts together:
- The
Searcher
connects itself to theFilterState
, and applies its filters with every search. - The
FilterState
connects to your productsLiveData
to invalidate search results when new filter are applied. - Finally, the
facetList
connects to its adapter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class MyViewModel : ViewModel() {
// Client, Searcher...
// Products
// Stats
// ...
val filterState = FilterState()
val facetList = FacetListConnector(
searcher = searcher,
filterState = filterState,
attribute = Attribute("category"),
selectionMode = SelectionMode.Single
)
val facetPresenter = FacetListPresenterImpl(
sortBy = listOf(FacetSortCriterion.CountDescending, FacetSortCriterion.IsRefined),
limit = 100
)
val connection = ConnectionHandler()
init {
// Search
// Stats
// ..
connection += facetList
connection += searcher.connectFilterState(filterState)
connection += filterState.connectPagedList(products)
}
override fun onCleared() {
super.onCleared()
searcher.cancel()
connection.clear()
}
}
To display your facets, create a facet_fragment.xml
layout with a RecyclerView
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_height="?attr/actionBarSize"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/facetList"
android:background="#FFFFFF"
app:layout_constraintTop_toBottomOf="@id/toolbar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_width="0dp"
android:layout_height="0dp"
tools:listitem="@layout/facet_item"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Create a FacetFragment
and configure your RecyclerView
with its adapter and LayoutManager
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class FacetFragment : Fragment() {
private val connection = ConnectionHandler()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.facet_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val viewModel = ViewModelProvider(requireActivity())[MyViewModel::class.java]
val adapterFacet = FacetListAdapter(MyFacetListViewHolder.Factory)
facetList.let {
it.adapter = adapterFacet
it.layoutManager = LinearLayoutManager(requireContext())
it.autoScrollToStart(adapterFacet)
}
connection += viewModel.facetList.connectView(adapterFacet, viewModel.facetPresenter)
}
override fun onDestroyView() {
super.onDestroyView()
connection.clear()
}
}
Add the code to switch to FacetFragment
in MainActivity
with “navigation up” support.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
showProductFragment()
}
fun showProductFragment() {
supportFragmentManager
.beginTransaction()
.add(R.id.container, ProductFragment())
.commit()
}
fun showFacetFragment() {
supportFragmentManager
.beginTransaction()
.add(R.id.container, FacetFragment())
.addToBackStack("facet")
.commit()
}
override fun onSupportNavigateUp(): Boolean {
supportFragmentManager.popBackStack()
return super.onSupportNavigateUp()
}
}
Add a filters button in product_fragment.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:clipToPadding="false">
<com.google.android.material.button.MaterialButton
android:id="@+id/filters"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="6dp"
android:layout_marginEnd="12dp"
android:text="Filters"
android:textAppearance="@style/TextAppearance.MaterialComponents.Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/searchView"
app:layout_constraintTop_toTopOf="parent" />
<androidx.appcompat.widget.SearchView
android:id="@+id/searchView"
android:layout_width="0dp"
android:layout_height="0dp"
android:focusable="false"
app:iconifiedByDefault="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/filters"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.Toolbar>
<TextView
android:id="@+id/stats"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:padding="16dp"
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/toolbar" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/productList"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/stats"
tools:listitem="@layout/product_item" />
</androidx.constraintlayout.widget.ConstraintLayout>
In ProductFragment
, add a listener to the filters button to switch to FacetFragment
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class ProductFragment : Fragment() {
private val connection = ConnectionHandler()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.product_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val viewModel = ViewModelProvider(requireActivity())[MyViewModel::class.java]
// Hits
// SearchBox
// Stats
// ...
filters.setOnClickListener { (requireActivity() as MainActivity).showFacetFragment() }
}
override fun onDestroyView() {
super.onDestroyView()
connection.clear()
}
}
You can now build and run your application to see your advanced search experience. This experience helps your users to filter search results and find exactly what they’re looking for.
Improving the user experience: Highlighting
Highlighting enhances the user experience by putting emphasis on the parts of the result that match the query. It’s a visual indication of why a result is relevant to the query.
You can add highlighting by implementing the Highlightable
interface on Product
.
First, define a highlightedName
field to retrieve the highlighted value for the name
attribute.
1
2
3
4
5
6
7
8
data class Product(
val name: String,
override val _highlightResult: JsonObject?
) : Highlightable {
public val highlightedName: HighlightedString?
get() = getHighlight(Attribute("name"))
}
Modify your SearcherSingleIndexDataSource
constructor to inject the highlighted values into each of your Product
objects.
1
2
3
4
5
6
7
8
9
10
11
12
13
class MyViewModel : ViewModel() {
// ...
val dataSourceFactory = SearcherSingleIndexDataSource.Factory(searcher) { hit ->
Product(
hit.json.getPrimitive("name").content,
hit.json.getObjectOrNull("_highlightResult")
)
}
// ...
}
Use the .toSpannedString()
extension function to convert an HighlightedString
into a SpannedString
that can be assigned to a TextView
to display the highlighted names.
1
2
3
4
5
6
class ProductViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
fun bind(product: Product) {
view.productName.text = product.highlightedName?.toSpannedString() ?: product.name
}
}
Conclusion
You now have a fully working search experience: your users can search for products, refine their results, and understand how many records are returned and why they’re relevant to the query.
You can find the full source code in the GitHub repository.
Going further
This is only an introduction to what you can do with InstantSearch Android: check out the widget showcase to see more components.