Search code examples
androidandroid-actionbarnativescriptsearchviewsearchbar

How to add a SearchView in an ActionBar on NativeScript Android (like WhatsApp)?


I would like to add a SearchView in an ActionBar on NativeScript Android.

The same shown in the Material Design Guide and used on WhatsApp when you click on the search icon.

Below are examples that I can not "convert" for NativeScript:

How to implement SearchView in ActionBar in Android

Android: Add searchView on the Action Bar

Android - Using SearchView in Toolbar/ActionBar with "Gmail style" ListView

Thank you :)


Solution

  • You will add SearchBar to ActionBar and toggle it's visibility just like the example you linked.

    XML

    <ActionBar title="Home">
        <SearchBar visibility="{{ show, show ? 'visible' : 'hidden' }}"
            clear="onToggleSearchBar">
        </SearchBar>
        <ActionItem visibility="{{ show, show ? 'hidden' : 'visible' }}"
            text="Search" tap="onToggleSearchBar"></ActionItem>
    </ActionBar>
    

    TS

    export function onToggleSearchBar(args: EventData) {
        (args.object as any).bindingContext.show = !(args.object as any).bindingContext.show;
    }
    

    ViewModel

    export class HomeViewModel extends Observable {
        @ObservableProperty() show: boolean = false;
    
        constructor() {
            super();
        }
    }
    

    Playground Sample