<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Darush on Medium]]></title>
        <description><![CDATA[Stories by Darush on Medium]]></description>
        <link>https://medium.com/@darush?source=rss-12b942034a32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*h9aG-AapnLTCUe_XGe9Zgg.jpeg</url>
            <title>Stories by Darush on Medium</title>
            <link>https://medium.com/@darush?source=rss-12b942034a32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:45:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@darush/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build a Simple Sort and Filter Screen in Your Android App]]></title>
            <link>https://medium.com/@darush/build-a-simple-sort-and-filter-screen-in-your-android-app-318f0d86e228?source=rss-12b942034a32------2</link>
            <guid isPermaLink="false">https://medium.com/p/318f0d86e228</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[material-design]]></category>
            <dc:creator><![CDATA[Darush]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 17:08:26 GMT</pubDate>
            <atom:updated>2026-02-13T22:38:39.147Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This story was written with the assistance of an AI writing program.</em></p><p>When your app presents large amounts of data in a list, users typically want more control over how they interact with it. They commonly use sorting and filtering to achieve this control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*zGS8WSJgarWmMt5MUl_VSA.gif" /></figure><p>In this post, I’ll demonstrate the implementation of a simple sort and filter functionality. The app retrieves a list of European countries from the <a href="https://restcountries.com/">https://restcountries.com/</a> API and provides two sorting options: by <strong>country name</strong> and <strong>population</strong>, along with filtering by <strong>sub-region</strong>.</p><p>This app employs various Android tools and components, including <strong>Google Material 3</strong>, <strong>Hilt</strong>, <strong>Retrofit</strong>, <strong>Paging</strong>, <strong>Navigation component</strong>, and <strong>Data binding</strong>.</p><p>The implementation code for this project can be found on my GitHub repository at <a href="https://github.com/IAmDarush/Rest-Countries-Sample">https://github.com/IAmDarush/Rest-Countries-Sample</a>.</p><p>Let’s delve into the code!</p><h3>Implementation</h3><p>This post will solely concentrate on the UI layer and design implementation of the app, without delving into other layers like networking or dependency injection. If you’re interested in learning about those aspects, feel free to explore the <a href="https://github.com/IAmDarush/Rest-Countries-Sample">source code repository</a>.</p><h4><a href="https://github.com/IAmDarush/Rest-Countries-Sample/blob/main/app/src/main/res/layout/bottom_sheet_filter.xml">bottom_sheet_filter.xml</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*1ffaa5mqHYzDUJpZesYfMw.png" /></figure><p>I chose to use a <strong>modal bottom sheet</strong> for the sort and filter screen since it fitted the style and design preferences of this app, though a dialog, fragment, or activity could also work.</p><p>Incorporating design elements like <strong>Chips</strong>, I added <a href="https://github.com/material-components/material-components-android/blob/master/docs/components/Chip.md#multiple-exclusion-scope">single-select and multi-select ChipGroup behaviors</a> for Sort type and Subregion filters, respectively.</p><p>I also used a <strong>Badge</strong> component, on top of the “<strong>Reset All</strong>” button, to indicate the number of user’s selections. To customize the badge attributes, I created a file named “<strong>filter_badge.xml</strong>” with the following content and placed it inside <strong>res/xml</strong> folder.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;badge xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    style=&quot;@style/Widget.Material3.Badge&quot;<br>    app:badgeGravity=&quot;TOP_END&quot;<br>    app:badgeWidePadding=&quot;8dp&quot;<br>    app:badgeWithTextHeight=&quot;24dp&quot;<br>    app:badgeWithTextWidth=&quot;24dp&quot;<br>    app:horizontalOffset=&quot;20dp&quot;<br>    app:maxCharacterCount=&quot;3&quot;<br>    app:verticalOffset=&quot;20dp&quot; /&gt;</pre><p>To learn more about the material components used, you can visit the Google’s Material Design system official guides:</p><ul><li>Bottom Sheets: <a href="https://m3.material.io/components/bottom-sheets/overview">https://m3.material.io/components/bottom-sheets/overview</a></li><li>Chips: <a href="https://m3.material.io/components/chips/overview">https://m3.material.io/components/chips/overview</a></li><li>Badges: <a href="https://m3.material.io/components/badges/overview">https://m3.material.io/components/badges/overview</a></li></ul><h4><a href="https://github.com/IAmDarush/Rest-Countries-Sample/blob/main/app/src/main/java/com/example/restcountries/ui/filter/FilterBottomSheet.kt">FilterBottomSheet.kt</a></h4><p>This class inflates the design layout file, connects the view model to the views, and handles user interactions. To accomplish this, it extends <strong>BottomSheetDialogFragment</strong> — a variation of DialogFragment specifically designed to display bottom sheets using BottomSheetDialog instead of a floating dialog.</p><p>Let’s eliminate the boilerplate in this post and only focus on the relevant code. You can always visit the <a href="https://github.com/IAmDarush/Rest-Countries-Sample/blob/main/app/src/main/java/com/example/restcountries/ui/filter/FilterBottomSheet.kt">repository</a> for the complete code.</p><pre>class FilterBottomSheet : BottomSheetDialogFragment() {<br><br>    private var _binding: BottomSheetFilterBinding? = null<br>    private val binding get() = _binding!!<br>    private val countriesViewModel: CountriesViewModel by navGraphViewModels(R.id.countriesNavGraph) {<br>        defaultViewModelProviderFactory<br>    }<br>    private val viewModel: FilterViewModel by viewModels()<br>    private var badgeDrawable: BadgeDrawable? = null<br><br>    ...<br><br>    @OptIn(ExperimentalBadgeUtils::class)<br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br><br>        ...<br><br>        binding.cgSortTypes.setOnCheckedStateChangeListener { _, checkedIds -&gt;<br>            if (checkedIds.isEmpty()) viewModel.setSortType(SortType.NONE)<br>            else when (checkedIds.first()) {<br>                R.id.chipAlphabeticalSort -&gt; viewModel.setSortType(SortType.ALPHABETICAL_ASC)<br>                R.id.chipByPopulationSort -&gt; viewModel.setSortType(SortType.POPULATION_ASC)<br>            }<br>        }<br><br>        for (index in 0 until binding.cgSubregion.childCount) {<br>            val chip = binding.cgSubregion.getChildAt(index) as Chip<br>            val subregion = getSubregionFromString(chip.text.toString())<br>            requireNotNull(subregion) { &quot;subregion must not be null&quot; }<br>            chip.isChecked = viewModel.uiState.value.subregions.contains(subregion)<br>            chip.setOnCheckedChangeListener { _, isChecked -&gt;<br>                if (isChecked) viewModel.selectSubregion(subregion)<br>                else viewModel.deselectSubregion(subregion)<br>            }<br>        }<br><br>        lifecycleScope.launch {<br>            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {<br>                launch {<br>                    viewModel.uiState.map { it.filterCount }.distinctUntilChanged()<br>                        .collect { count -&gt;<br>                            updateBadgeDrawable(count)<br>                        }<br>                }<br><br>                launch {<br>                    viewModel.uiState.map { it.applyAllFilters }.distinctUntilChanged()<br>                        .collect { shouldApplyFilters -&gt;<br>                            if (shouldApplyFilters) {<br>                                val filterData = FilterData(<br>                                    sortType = viewModel.uiState.value.sortType,<br>                                    subregions = viewModel.uiState.value.subregions<br>                                )<br>                                countriesViewModel.applyFilters(filterData)<br>                                dismiss()<br>                            }<br>                        }<br>                }<br><br>                launch {<br>                    viewModel.uiState.map { it.clearAllFilters }.distinctUntilChanged()<br>                        .collect { shouldResetFilters -&gt;<br>                            if (shouldResetFilters) {<br>                                countriesViewModel.resetFilters()<br>                                dismiss()<br>                            }<br>                        }<br>                }<br>            }<br>        }<br><br>    }<br><br>    ...<br><br>}</pre><p>First, to handle Sort type changes, I’m adding a checked state listener in the OnCreateView() method.</p><p>Next, as multiple selections are allowed for subregion filter, I’m adding listeners for each subregion Chip.</p><p>Finally, I’m observing the UI state changes and performing relevant actions, such as updating the badge drawable state, applying filters and resetting filters on the calling view model.</p><h4><a href="https://github.com/IAmDarush/Rest-Countries-Sample/blob/main/app/src/main/java/com/example/restcountries/ui/filter/FilterViewModel.kt">FilterViewModel.kt</a></h4><p>This class handles the communication and data management between the XML layout file<strong> bottom_sheet_filter.xml</strong> and <strong>FilterBottomSheet</strong> fragment.</p><pre>package com.example.restcountries.ui.filter<br><br>import androidx.lifecycle.SavedStateHandle<br>import androidx.lifecycle.ViewModel<br>import com.example.restcountries.data.model.SortType<br>import com.example.restcountries.data.model.Subregion<br>import kotlinx.coroutines.flow.MutableStateFlow<br>import kotlinx.coroutines.flow.asStateFlow<br>import kotlinx.coroutines.flow.update<br><br>const val KEY_FILTER_DATA = &quot;filter_data&quot;<br><br>data class FilterData(<br>    val sortType: SortType = SortType.NONE,<br>    val subregions: Set&lt;Subregion&gt; = setOf()<br>) : java.io.Serializable<br><br>class FilterViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {<br><br>    data class UiState(<br>        val sortType: SortType = SortType.NONE,<br>        val subregions: Set&lt;Subregion&gt; = setOf(),<br>        val clearAllFilters: Boolean = false,<br>        val applyAllFilters: Boolean = false<br>    ) {<br>        val filterCount: Int<br>            get() {<br>                val sortCount = if (sortType == SortType.NONE) 0 else 1<br>                val filterCount = subregions.size<br>                return sortCount + filterCount<br>            }<br><br>        val chipAlphabeticalSortIsChecked = sortType == SortType.ALPHABETICAL_ASC<br>        val chipByPopulationSortIsChecked = sortType == SortType.POPULATION_ASC<br>    }<br><br>    private val _uiState = MutableStateFlow(UiState())<br>    val uiState = _uiState.asStateFlow()<br><br>    init {<br><br>        savedStateHandle.get&lt;FilterData&gt;(KEY_FILTER_DATA)?.let { filterData -&gt;<br>            _uiState.update {<br>                it.copy(sortType = filterData.sortType, subregions = filterData.subregions)<br>            }<br>        }<br><br>    }<br><br>    fun setSortType(sortType: SortType) {<br>        _uiState.update {<br>            it.copy(sortType = sortType)<br>        }<br>    }<br><br>    fun selectSubregion(subregion: Subregion) {<br>        _uiState.update {<br>            val subregions = it.subregions.toMutableSet().apply {<br>                add(subregion)<br>            }<br>            it.copy(subregions = subregions)<br>        }<br>    }<br><br>    fun deselectSubregion(subregion: Subregion) {<br>        _uiState.update {<br>            val subregions = it.subregions.toMutableSet().apply {<br>                remove(subregion)<br>            }<br>            it.copy(subregions = subregions)<br>        }<br>    }<br><br>    fun resetFilters() {<br>        _uiState.update {<br>            it.copy(clearAllFilters = true, subregions = setOf(), sortType = SortType.NONE)<br>        }<br>    }<br><br>    fun applyFilters() {<br>        _uiState.update {<br>            it.copy(applyAllFilters = true)<br>        }<br>    }<br><br>}</pre><p>The calling Android component — in our case <strong>CountriesFragment</strong> — passes the data to the <strong>FilterViewModel</strong> using an object of the serializable data class <strong>FilterData</strong>. To check for any previous sort and filter states, I’m using <strong>savedStateHandle</strong> with the <strong>KEY_FILTER_DATA</strong> as the key, updating the <strong>uiState</strong> accordingly.</p><p>The remaining methods are just public state mutators that can be accessed by the views.</p><h3>Addressing Some Quirks</h3><p>While developing this project, I encountered some exceptional cases that required special consideration and attention.</p><p>The first one was that the bottom sheet was not fully expanded inside its parent view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*T-i3plhVkvFk5G4C8QlObw.png" /><figcaption>Bottom sheet content not fully expanded to match the parent height</figcaption></figure><p>To address this issue, I included the following code in the <strong>onViewCreated</strong>() method of the <strong>FilterBottomSheet</strong> with credit to <a href="https://stackoverflow.com/questions/37555403/android-bottomsheetdialogfragment-does-not-expand-completely">this Stack Overflow answer</a>.</p><pre>requireDialog().setOnShowListener {<br>    val bottomSheetBehavior = BottomSheetBehavior.from(binding.bottomSheet)<br>    bottomSheetBehavior.isHideable = false<br>    val bottomSheetParent = binding.bottomSheetParent<br>    BottomSheetBehavior.from(bottomSheetParent.parent as View).peekHeight =<br>        bottomSheetParent.height<br>    bottomSheetBehavior.peekHeight = bottomSheetParent.height<br>    bottomSheetParent.parent.requestLayout()<br>}</pre><p>I encountered another issue with the badge drawable where it would not attach to the specified position and would disappear after a chip was selected. To address this problem, I included the following code in the <strong>onViewCreated() </strong>method:</p><pre>// Prepare the filters badge once the views are laid out<br>binding.btnResetAll.viewTreeObserver.addOnGlobalLayoutListener(object :<br>    ViewTreeObserver.OnGlobalLayoutListener {<br>    @OptIn(ExperimentalBadgeUtils::class)<br>    override fun onGlobalLayout() {<br>        badgeDrawable =<br>            BadgeDrawable.createFromResource(requireContext(), R.xml.filter_badge).apply {<br>                horizontalOffsetWithText = binding.frameLayout.width / 4<br>                verticalOffsetWithText =<br>                    binding.frameLayout.height / 2 + ViewUtils.dpToPx(resources, 24f)<br>                        .toInt() / 2<br>                BadgeUtils.attachBadgeDrawable(<br>                    this, binding.btnResetAll, binding.frameLayout<br>                )<br>            }<br>        updateBadgeDrawable(viewModel.uiState.value.filterCount)<br>        binding.btnResetAll.viewTreeObserver.removeOnGlobalLayoutListener(this)<br>    }<br>})</pre><p>That wraps up our look at creating a sort and filter sheet in Android. I hope this article has been helpful and informative for you. Please feel free to share any feedback or comments you may have. Happy coding! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=318f0d86e228" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>