API Reference / Android Widgets / SortBy
Apr. 24, 2019

About this widget

SortBy displays a list of indices, allowing a user to change the way hits are sorted (using replica indices). Another common use case is to let the user switch between different indices to show different results.

For this to work, you must define all indices that you pass to SortBy as replicas of the main index.

To add SortBy to your search experience, use these components:

  • Searcher: The Searcher that handles your searches.
  • SortByViewModel: The logic applied to the index sorting/switching.
  • SortByViewAutocomplete: The concrete view implementing SortByView.
  • IndexPresenter: Optional. The presenter that converts an Index to a String output.

Examples

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 MyActivity : AppCompatActivity() {

    val client = ClientSearch(
        ApplicationID("YourApplicationID"),
        APIKey("YourAPIKey")
    )
    val index = client.initIndex(IndexName("YourIndexName"))
    val indexAsc = client.initIndex(IndexName("YourIndexName_ASC"))
    val indexDesc = client.initIndex(IndexName("YourIndexName_DESC"))
    val searcher = SearcherSingleIndex(index)
    val indexes = mapOf(
        0 to index,
        1 to indexAsc,
        2 to indexDesc
    )
    val viewModel = SortByViewModel(indexes)
    val connection = ConnectionHandler()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val autoCompleteTextView = AutoCompleteTextView(this)
        val adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1)
        val view = SortByViewAutocomplete(autoCompleteTextView, adapter)

        connection += viewModel.connectSearcher(searcher)
        connection += viewModel.connectView(view)

        searcher.searchAsync()
    }

    override fun onDestroy() {
        super.onDestroy()
        connection.disconnect()
        searcher.cancel()
    }
}

Parameters

indexes
type: Map<Int, Index>
Required

The list of indices to search in.

1
2
3
4
5
6
private val indexes = mapOf(
        0 to indexTitle,
        1 to indexYearAsc,
        2 to indexYearDesc
    )
SortByViewModel(indexes = indexes)
selected
type: Int?
Optional

The index to select. By default, none is selected.

1
SortByViewModel(indexes, selected = 0)

Presenter

Index Presenter
type: IndexPresenter
default: IndexPresenterImpl()
Optional

The presenter that defines the way we want to display an index, taking as input an Index and returning a String.

1
2
3
4
5
6
7
8
9
val presenter: (Index) -> String = { index ->
    when (index) {
        indexTitle -> "Default"
        indexYearAsc -> "Year Asc"
        indexYearDesc -> "Year Desc"
        else -> index.indexName.raw
    }
}
sortByViewModel.connectView(view, presenter)

Did you find this page helpful?