Introduction
In this blog, we are going to learn about how to search the items in Listview in Xamarin Android app.
Solution
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)
- <!-- Editext for Search -->
- <EditText
- android:id="@+id/inputSearch"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:hint="Search"
- android:inputType="textVisiblePassword"
- android:background="@android:color/white"
- android:paddingBottom="10dp"
- android:paddingLeft="5dp"
- android:paddingRight="5dp"
- android:paddingTop="10dp"
- 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)
-
- EditText inputSearch;
- 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)
- 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)
- private void InputSearch_TextChanged(object sender, TextChangedEventArgs e)
- {
-
- var searchText = inputSearch.Text;
-
-
- List<User> list = (from items in UserData.Users
- where items.Name.Contains(searchText) ||
- items.Department.Contains(searchText) ||
- items.Details.Contains(searchText)
- select items).ToList<User>();
-
-
- myList.Adapter = new MyCustomListAdapter(list);
- }
Now, we are done with the implementation to see the results Run the Application.
Output