API Reference / Android Widgets / hits
Apr. 11, 2019
Widget signature
<com.algolia.instantsearch.ui.views.Hits
  android:id="@+id/hits"
  algolia:itemLayout="@layout/hits_item"

  <!-- Optional parameters -->
  algolia:infiniteScroll="boolean"
  algolia:remainingItemsBeforeLoading="integer"
  algolia:autoHideKeyboard="boolean"
  algolia:variant="string"
/>

About this widget

The Hits widget is made to display a list of results. Built over a RecyclerView, it displays a limited window into a large data set of search results.

Examples

1
2
3
4
5
6
7
<com.algolia.instantsearch.ui.views.Hits
    android:id="@+id/hits"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    algolia:remainingItemsBeforeLoading="5"
    algolia:autoHideKeyboard="true"
    algolia:itemLayout="@layout/hits_item" />

Parameters

itemLayout
type: reference
Required

Determine the appearances of the search results, by providing a layout used to display each record. When receiving results from its Searcher, this widget binds the given layout to each result to display its attributes in the appropriate Views.

Note that you must enable Data Binding for this feature to work.

1
algolia:itemLayout="@layout/hits_item"
infiniteScroll
type: boolean
default: true

If false, disables the infinite scroll of the widget.

1
algolia:infiniteScroll="false"
remainingItemsBeforeLoading
type: integer
default: 5

The minimum number of remaining hits to load the next page. For example, if set to 10, the next page is loaded when there are less than 10 items below the last visible item.

1
algolia:remainingItemsBeforeLoading="10"
autoHideKeyboard
type: boolean
default: false

Whether the keyboard should close when the user scrolls down.

1
algolia:autoHideKeyboard="true"
variant
type: string

An identifier for the widget group this widget is part of. If specified, this widget is only linked to other widgets that have the same variant. See Multi-Index Searches.

1
algolia:variant="actors"

Data Binding

Data binding is done using the Android DataBinding Library, which lets you link a layout to an application’s data. To enable this feature, add dataBinding.enabled true to your app’s build.gradle under android:

1
2
3
4
android {
    dataBinding.enabled true
    //...
}

You can now create the hit layout. The layout file should use a <layout></layout> root node, followed by a regular ViewGroup (such as a LinearLayout). You can then describe what attributes should be mapped to each View, as follows:

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
<layout
    xmlns:algolia="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/contactFace"
            style="@style/AppTheme.View.ContactImage"
            algolia:attribute='@{"img"}'/>

        <TextView
            android:id="@+id/contactCompany"
            style="@style/AppTheme.View.ContactText.Small"
            algolia:attribute='@{"company"}'/>

        <RatingBar
            android:id="@+id/contactScore"
            style="@style/AppTheme.View"
            algolia:attribute='@{"score"}'/>
    </RelativeLayout>
</layout>

For each View which should receive a result’s attribute, you can specify algolia:attribute='@{"foo"}' to map the record’s foo attribute to this View.

Currently, the Hits widget natively handles the following Views and their subclasses:

View Class Use of the attribute Method called Notes
TextView text content setText(attributeValue) Can be highlighted
EditText hint content setHint(attributeValue) Can be highlighted
ImageView bitmap image URL setBitmapImage(attributeBitmap) Parsed to an URL, then loaded asynchronously
RatingBar rating value setRating(attributeValue) Parsed as Float
ProgressBar progress value setProgress(attributeValue) Parsed as Float and rounded to the nearest Integer

Custom hit views

Apart from these ones, any View can be used to hold an attribute if it implements the AlgoliaHitView interface. In this case, we call onUpdateView(JSONObject result) and the view is responsible of using the result’s JSON to display the hit.

For example, see the media app’s TimestampHitView, a TextView which transforms a timestamp attribute into a human-readable date.

Empty View

The Hits widget implements an empty view mechanism to display an alternative View if there are no results to display, following the AdapterView’s interface. If you add a View to your layout with the id @android:id/empty, it is displayed instead of the Hits when there is no data to display. You can also set it programmatically using Hits#setEmptyView(View).

Item Click Listener

As the Hits widget is based on a RecyclerView, we use Hugo Visser’s ItemClickSupport to let users react to clicks on individual hits. To do so, add an OnItemClickListener to the hits:

1
2
3
4
5
6
7
hits.setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
    @Override
    public void onItemClick(RecyclerView recyclerView, int position, View v) {
        JSONObject hit = hits.get(position);
        // Do something with the hit
    }
});

Prefixing and suffixing attributes

You might need to apply a prefix or suffix to a View’s attribute value. A common use case is image attributes with a relative path (like foo.png), requiring a prefix like https://example.com/files/ to get the full image path.

To achieve this, you can add either or both prefix/suffix attributes to your view. For example, if your attribute value is foo but you want the full value to be https://example.com/files/foo.png:

1
2
3
4
5
<ImageView
    android:id="@+id/name"
    algolia:attribute='@{"image"}'
    algolia:prefix='@{"https://example.com/files/"}'
    algolia:suffix='@{".png"}'/>

Highlighting

Visually highlighting the search result is an essential feature of a search interface. It helps users understand the results by showing them why a result is relevant to their query.

The Hits widget automatically handles highlighting. To highlight a textual attribute, simply add the highlighted attribute on its view:

1
2
3
4
<TextView
    android:id="@+id/name"
    algolia:attribute='@{"city"}'
    algolia:highlighted="@{true}"/>

This highlights the attribute according to the query term. The default color used for highlighting is R.color.colorHighlighting, which you can override in your application.

You can also specify algolia:highlightColor='@{R.color.color_foo}' on a View to use a specific color only for this one.

Note that highlighting only works automatically on TextViews. if you implement a custom hit view, or want to highlight results received by your custom widget, you should use the Highlighter. This tool lets you build a highlighted Spannable from a search result and provides an optional highlight color:

1
2
3
4
5
6
7
final Spannable highlightedAttribute = Highlighter.getDefault()
                                                  .setInput(result, attributeToHighlight)       // either using Algolia's _highlightResult
                                                  .setInput("My <em> highlighted</em> string")  // or using a raw markup string
                                                  .setColor(context)                            // either using the default R.color.colorHighlighting
                                                  .setColor(Color.RED)                          // or using a system Color int
                                                  .setColor(R.color.myColor, context)           // or using a ColorRes
                                                  .render();

The default Highlighter highlights anything between <em> and </em>. You can configure the Highlighter to highlight between any pair of terms with Highlighter.setDefault(newPrefix, newSuffix), or use a regular expression to highlight any captured part with Highlighter.setDefault(newPattern).

For example, see the e-commerce app’s CategoryOrTypeView, a TextView which takes either the category or the type attribute of a record and highlights it before displaying.

Did you find this page helpful?