Searching Items In ListView Xamarin Android


In this blog, we are going to learn about how to search the items in Listview in Xamarin Android app.


As we created custom ListView in my last blog, so in this solution, we are going to add the search view to filter the list. To add search in ListView, follow the steps given below.

Step 1

Open the custom ListView solution and open Main.axml file and add an edit text, as shown below.

(File Name: Main.axml) 

  1. <!-- Editext for Search -->  
  2.     <EditText  
  3.         android:id="@+id/inputSearch"  
  4.         android:layout_width="fill_parent"  
  5.         android:layout_height="wrap_content"  
  6.         android:hint="Search"  
  7.         android:inputType="textVisiblePassword"  
  8.         android:background="@android:color/white"  
  9.         android:paddingBottom="10dp"  
  10.         android:paddingLeft="5dp"  
  11.         android:paddingRight="5dp"  
  12.         android:paddingTop="10dp"  
  13.         android:textColor="#000000"/>   

Step 2

Now, go to Main Activity and add the lines of code given below to initialise Edit Text, 

(File Name: MainActivity.cs) 

  1. // Intialize EditText  
  2. EditText inputSearch;  
  3. inputSearch = FindViewById<EditText>(Resource.Id.inputSearch);  

Step 3

Now add a Text Change Listener to the Edit Text, as shown below.

(File Name: MainActivity.cs)

  1. inputSearch.TextChanged += InputSearch_TextChanged;  

Step 4

Implement the TextChanged listener, as it checks for the input text, checks it with the list and show the appropriate result.

(File Name: MainActivity.cs) 

  1. private void InputSearch_TextChanged(object sender, TextChangedEventArgs e)  
  2.         {    
  3.             //get the text from Edit Text            
  4.             var searchText = inputSearch.Text;  
  6.             //Compare the entered text with List  
  7.             List<User> list = (from items in UserData.Users  
  8.                                where items.Name.Contains(searchText) ||  
  9.                                               items.Department.Contains(searchText) ||  
  10.                                               items.Details.Contains(searchText)                                               
  11.                                         select items).ToList<User>();  
  13.             // bind the result with adapter  
  14.             myList.Adapter = new MyCustomListAdapter(list);  
  15.         }   

Now, we are done with the implementation to see the results Run the Application.


Next Recommended Reading Creating ListView In Xamarin Android