> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-llms-scoped-indexes.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Search

> Real-time search interface for finding conversations and messages with filters, scopes, and customization options.

<Accordion title="AI Integration Quick Reference">
  ```json theme={null}
  {
    "component": "CometChatSearch",
    "package": "com.cometchat.chatuikit.search",
    "xmlElement": "<com.cometchat.chatuikit.search.CometChatSearch />",
    "description": "Real-time search interface for finding conversations and messages with filters, scopes, and customization options.",
    "primaryOutput": {
      "conversationClicked": {
        "method": "setOnConversationClicked",
        "type": "OnItemClick<Conversation>"
      },
      "messageClicked": {
        "method": "setOnMessageClicked",
        "type": "OnItemClick<BaseMessage>"
      }
    },
    "methods": {
      "data": {
        "setConversationsRequestBuilder": {
          "type": "ConversationsRequest.ConversationsRequestBuilder",
          "default": "SDK default",
          "note": "Pass the builder, not the result of .build()"
        },
        "setMessagesRequestBuilder": {
          "type": "MessagesRequest.MessagesRequestBuilder",
          "default": "SDK default",
          "note": "Pass the builder, not the result of .build()"
        }
      },
      "callbacks": {
        "setOnConversationClicked": "OnItemClick<Conversation>",
        "setOnMessageClicked": "OnItemClick<BaseMessage>",
        "setOnBackPressListener": "OnBackPress",
        "setOnError": "OnError",
        "setOnEmpty": "OnEmpty",
        "setOnLoadMessages": "OnLoad<BaseMessage>",
        "setOnLoadConversations": "OnLoad<Conversation>"
      },
      "visibility": {
        "setEmptyStateVisibility": { "type": "int (View.VISIBLE | View.GONE)", "default": "View.VISIBLE" },
        "setErrorStateVisibility": { "type": "int", "default": "View.VISIBLE" }
      },
      "functionality": {
        "setUid": { "type": "String", "note": "Scope search to a specific user conversation" },
        "setGuid": { "type": "String", "note": "Scope search to a specific group conversation" },
        "setSearchFilters": { "type": "List<UIKitConstants.SearchFilter>", "note": "Filters rendered as chips" },
        "setInitialSearchFilter": { "type": "UIKitConstants.SearchFilter", "note": "Default active filter on load" },
        "setSearchIn": { "type": "List<SearchScope>", "note": "Entities to search in" },
        "setHideGroupType": { "type": "boolean", "default": "false" },
        "setHideUserStatus": { "type": "boolean", "default": "false" }
      },
      "viewSlots": {
        "setConversationItemView": "ConversationsSearchViewHolderListener — entire conversation item row",
        "setTextMessageItemView": "MessagesSearchViewHolderListener<TextMessage> — text message item",
        "setImageMessageItemView": "MessagesSearchViewHolderListener<MediaMessage> — image message item",
        "setAudioMessageItemView": "MessagesSearchViewHolderListener<MediaMessage> — audio message item",
        "setVideoMessageItemView": "MessagesSearchViewHolderListener<MediaMessage> — video message item",
        "setDocumentMessageItemView": "MessagesSearchViewHolderListener<MediaMessage> — document message item",
        "setLinkMessageItemView": "MessagesSearchViewHolderListener<TextMessage> — link message item",
        "setInitialView": "@LayoutRes int — initial state before search",
        "setEmptyView": "@LayoutRes int — empty state",
        "setLoadingView": "View — loading state",
        "setErrorView": "View — error state"
      },
      "advanced": {
        "setTextFormatters": "List<CometChatTextFormatter> — custom text formatters",
        "setDateTimeFormatter": "DateTimeFormatterCallback — custom date/time formatting",
        "setMentionAllLabelId": "String id, String mentionAllLabel — custom mention-all label",
        "setHintText": "String — search bar hint text"
      },
      "style": {
        "setStyle": {
          "type": "@StyleRes int",
          "parent": "CometChatSearchStyle"
        }
      }
    },
    "events": [],
    "sdkListeners": []
  }
  ```
</Accordion>

## Where It Fits

`CometChatSearch` is a composite search component. It searches across conversations and messages in real time and emits the selected result via `setOnConversationClicked` or `setOnMessageClicked`. Wire it to navigation so tapping a conversation opens the message view, or tapping a message scrolls to it in context.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin ChatActivity.kt lines theme={null}
    class ChatActivity : AppCompatActivity() {

        private lateinit var search: CometChatSearch
        private lateinit var messageHeader: CometChatMessageHeader
        private lateinit var messageList: CometChatMessageList
        private lateinit var messageComposer: CometChatMessageComposer

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_chat)

            search = findViewById(R.id.cometchat_search)
            messageHeader = findViewById(R.id.message_header)
            messageList = findViewById(R.id.message_list)
            messageComposer = findViewById(R.id.message_composer)

            search.setOnConversationClicked { view, position, conversation ->
                val user = conversation.conversationWith as? User
                user?.let {
                    messageHeader.setUser(it)
                    messageList.setUser(it)
                    messageComposer.setUser(it)
                }
            }

            search.setOnMessageClicked { view, position, baseMessage ->
                // Navigate to the message in context
            }
        }
    }
    ```
  </Tab>

  <Tab title="Java">
    ```java ChatActivity.java lines theme={null}
    public class ChatActivity extends AppCompatActivity {

        private CometChatSearch search;
        private CometChatMessageHeader messageHeader;
        private CometChatMessageList messageList;
        private CometChatMessageComposer messageComposer;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_chat);

            search = findViewById(R.id.cometchat_search);
            messageHeader = findViewById(R.id.message_header);
            messageList = findViewById(R.id.message_list);
            messageComposer = findViewById(R.id.message_composer);

            search.setOnConversationClicked((view, position, conversation) -> {
                if (conversation.getConversationWith() instanceof User) {
                    User user = (User) conversation.getConversationWith();
                    messageHeader.setUser(user);
                    messageList.setUser(user);
                    messageComposer.setUser(user);
                }
            });

            search.setOnMessageClicked((view, position, baseMessage) -> {
                // Navigate to the message in context
            });
        }
    }
    ```
  </Tab>
</Tabs>

## Quick Start

Add the component to your layout XML:

```xml activity_search.xml lines theme={null}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.activity.SearchActivity">

    <com.cometchat.chatuikit.search.CometChatSearch
        android:id="@+id/cometchat_search"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
```

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-llms-scoped-indexes/zZz-wQk_4Cpgg3y_/images/android-search-overview.png?fit=max&auto=format&n=zZz-wQk_4Cpgg3y_&q=85&s=eae25596187079b24c6a02f87561541d" width="2560" height="1670" data-path="images/android-search-overview.png" />
</Frame>

Prerequisites: CometChat SDK initialized with `CometChatUIKit.init()`, a user logged in, and the `cometchat-chat-uikit-android` dependency added.

To add programmatically in an Activity:

<Tabs>
  <Tab title="Kotlin">
    ```kotlin SearchActivity.kt lines theme={null}
    class SearchActivity : AppCompatActivity() {
        private lateinit var binding: ActivitySearchBinding

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = ActivitySearchBinding.inflate(layoutInflater)
            setContentView(binding.root)
        }
    }
    ```
  </Tab>

  <Tab title="Java">
    ```java SearchActivity.java lines theme={null}
    public class SearchActivity extends AppCompatActivity {
        private ActivitySearchBinding binding;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            binding = ActivitySearchBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());
        }
    }
    ```
  </Tab>
</Tabs>

## Actions and Events

### Callback Methods

#### `setOnConversationClicked`

Fires when a user taps a conversation from the search results. Primary navigation hook — set the active conversation and render the message view.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin SearchActivity.kt lines theme={null}
    binding.cometchatSearch.setOnConversationClicked { view, position, conversation ->
        Log.i(TAG, "onCreate: Conversation Clicked !")
    }
    ```
  </Tab>

  <Tab title="Java">
    ```java SearchActivity.java lines theme={null}
    binding.cometchatSearch.setOnConversationClicked((view, position, conversation) -> {
        Log.d(TAG, "onCreate: Conversation Clicked !");
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Replaces the default conversation-click behavior. When a user taps a conversation item, your custom lambda executes. The callback receives the view, position, and `Conversation` object.

#### `setOnMessageClicked`

Fires when a user taps a message from the search results. Use to navigate to the message in context.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin SearchActivity.kt lines theme={null}
    binding.cometchatSearch.setOnMessageClicked { view, position, baseMessage ->
        Log.i(TAG, "onCreate: Message Clicked !")
    }
    ```
  </Tab>

  <Tab title="Java">
    ```java SearchActivity.java lines theme={null}
    binding.cometchatSearch.setOnMessageClicked((view, position, baseMessage) -> {
        Log.d(TAG, "onCreate: Message Clicked !");
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Registers a callback that fires when the user taps a message in the search results. The callback receives the view, position, and `BaseMessage` object.

#### `setOnBackPressListener`

Fires when the user presses the back button in the search bar. Default: no predefined behavior.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin SearchActivity.kt lines theme={null}
    binding.cometchatSearch.setOnBackPressListener {
        Log.i(TAG, "onCreate: Back Pressed !")
    }
    ```
  </Tab>

  <Tab title="Java">
    ```java SearchActivity.java lines theme={null}
    binding.cometchatSearch.setOnBackPressListener(() -> {
        Log.d(TAG, "onCreate: Back Pressed !");
    });
    ```
  </Tab>
</Tabs>

#### `setOnError`

Fires on internal errors (network failure, auth issue, SDK exception).

<Tabs>
  <Tab title="Kotlin">
    ```kotlin SearchActivity.kt lines theme={null}
    binding.cometchatSearch.onError = OnError {
        Log.i(TAG, "onCreate: Error Occurred ! ${it.message}")
    }
    ```
  </Tab>

  <Tab title="Java">
    ```java SearchActivity.java lines theme={null}
    binding.cometchatSearch.setOnError((e -> {
        Log.e(TAG, "onCreate: ", e);
    }));
    ```
  </Tab>
</Tabs>

#### `setOnLoadMessages`

Fires when the message list is successfully fetched and loaded, helping track when message search results are ready.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin SearchActivity.kt lines theme={null}
    binding.cometchatSearch.setOnLoadMessages(OnLoad<BaseMessage> { list ->
        Log.i(TAG, "Messages loaded: ${list.size}")
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java SearchActivity.java lines theme={null}
    binding.cometchatSearch.setOnLoadMessages(list -> {
        Log.d(TAG, "Messages loaded: " + list.size());
    });
    ```
  </Tab>
</Tabs>

#### `setOnLoadConversations`

Fires when the conversation list is successfully fetched and loaded, helping track when conversation search results are ready.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin SearchActivity.kt lines theme={null}
    binding.cometchatSearch.setOnLoadConversations(OnLoad<Conversation> { list ->
        Log.i(TAG, "Conversations loaded: ${list.size}")
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java SearchActivity.java lines theme={null}
    binding.cometchatSearch.setOnLoadConversations(list -> {
        Log.d(TAG, "Conversations loaded: " + list.size());
    });
    ```
  </Tab>
</Tabs>

#### `setOnEmpty`

Fires when the search returns no results, enabling custom handling such as showing a placeholder.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin SearchActivity.kt lines theme={null}
    binding.cometchatSearch.onEmpty = OnEmpty {
        Log.i(TAG, "onCreate: No Results Found !")
    }
    ```
  </Tab>

  <Tab title="Java">
    ```java SearchActivity.java lines theme={null}
    binding.cometchatSearch.setOnEmpty(() -> {
        Log.d(TAG, "onCreate: Empty Result !");
    });
    ```
  </Tab>
</Tabs>

* **Verify**: After setting an action callback, trigger the corresponding user interaction (tap a conversation result, tap a message result, press back, cause an error, or search for a term with no results) and confirm your custom logic executes.

### Global UI Events

The `CometChatSearch` component does not produce any global UI events.

### SDK Events (Real-Time, Automatic)

The `CometChatSearch` component does not listen to any SDK events internally. Search results are fetched on demand when the user types a query.

## Functionality

Small functional customizations such as toggling visibility of UI elements and configuring search scope.

| Methods | Description | Code |
| - | - | - |
| `setEmptyStateVisibility` | Hides the empty state when search returns no results | `.setEmptyStateVisibility(View.GONE);` |
| `setErrorStateVisibility` | Hides the error state on search failure | `.setErrorStateVisibility(View.GONE);` |
| `setSearchFilters` | List of filters rendered as chips in the search component | `.setSearchFilters(filters);` |
| `setInitialSearchFilter` | The filter which will be active by default on load | `.setInitialSearchFilter(UIKitConstants.SearchFilter.MESSAGES);` |
| `setSearchIn` | List of entities in which the search should be performed | `.setSearchIn(scopes);` |
| `setHideGroupType` | Hides the group type icon in conversation leading view | `.setHideGroupType(true);` |
| `setHideUserStatus` | Hides the user's online/offline status indicator | `.setHideUserStatus(true);` |

* **Verify**: After calling a visibility or functionality method, confirm the corresponding UI element is shown or hidden, or the search scope is correctly applied.

## Custom View Slots

Each slot replaces a section of the default UI. Conversation item slots use the `ConversationsSearchViewHolderListener` pattern (`createView` + `bindView`). Message item slots use the `MessagesSearchViewHolderListener` pattern.

| Slot | Method | Replaces |
| - | - | - |
| Conversation item view | `setConversationItemView(ConversationsSearchViewHolderListener)` | Entire conversation item row |
| Text message item | `setTextMessageItemView(MessagesSearchViewHolderListener<TextMessage>)` | Text message item |
| Image message item | `setImageMessageItemView(MessagesSearchViewHolderListener<MediaMessage>)` | Image message item |
| Audio message item | `setAudioMessageItemView(MessagesSearchViewHolderListener<MediaMessage>)` | Audio message item |
| Video message item | `setVideoMessageItemView(MessagesSearchViewHolderListener<MediaMessage>)` | Video message item |
| Document message item | `setDocumentMessageItemView(MessagesSearchViewHolderListener<MediaMessage>)` | Document message item |
| Link message item | `setLinkMessageItemView(MessagesSearchViewHolderListener<TextMessage>)` | Link message item |
| Initial view | `setInitialView(@LayoutRes int)` | Initial state before search |
| Empty view | `setEmptyView(@LayoutRes int)` | Empty state |
| Loading view | `setLoadingView(View)` | Loading spinner |
| Error view | `setErrorView(View)` | Error state |

### `setConversationItemView`

Replace the entire conversation item row in search results.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin SearchActivity.kt lines theme={null}
    binding.cometchatSearch.setConversationItemView(object : ConversationsSearchViewHolderListener() {
        override fun createView(context: Context?, listItem: View?): View? {
            return layoutInflater.inflate(R.layout.custom_conversation_search_item, null)
        }

        override fun bindView(
            context: Context?,
            createdView: View?,
            conversation: Conversation?,
            holder: RecyclerView.ViewHolder?,
            conversationList: List<Conversation?>?,
            position: Int
        ) {
            val titleTv = createdView?.findViewById<android.widget.TextView>(R.id.tv_title)
            conversation?.let {
                if (it.conversationType == CometChatConstants.CONVERSATION_TYPE_USER) {
                    titleTv?.text = (it.conversationWith as User).name
                } else {
                    titleTv?.text = (it.conversationWith as Group).name
                }
            }
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java SearchActivity.java lines theme={null}
    binding.cometchatSearch.setConversationItemView(new ConversationsSearchViewHolderListener() {
        @Override
        public View createView(Context context, View listItem) {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            return layoutInflater.inflate(R.layout.custom_conversation_search_item, null);
        }

        @Override
        public void bindView(Context context, View createdView, Conversation conversation, RecyclerView.ViewHolder holder, List<Conversation> conversationList, int position) {
            android.widget.TextView titleTv = createdView.findViewById(R.id.tv_title);
            if (conversation != null) {
                if (conversation.getConversationType().equals(CometChatConstants.CONVERSATION_TYPE_USER)) {
                    titleTv.setText(((User) conversation.getConversationWith()).getName());
                } else {
                    titleTv.setText(((Group) conversation.getConversationWith()).getName());
                }
            }
        }
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Registers a `ConversationsSearchViewHolderListener` for conversation items in search results. The `createView` method inflates a custom layout, and `bindView` populates it with the conversation name based on whether it's a user or group conversation.

### `setTextMessageItemView`

Replace the text message item view in search results.

Define a custom layout XML:

```xml custom_message_item_view.xml lines theme={null}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="16dp"
    android:background="#E8E4F3">

    <TextView
        android:id="@+id/tv_sender_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="George Alan:"
        android:textColor="#6B4FBB"
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_marginEnd="4dp" />

    <TextView
        android:id="@+id/tv_message"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="That works for me. Yes, let's go a..."
        android:textColor="#4A4A4A"
        android:textSize="16sp"
        android:ellipsize="end"
        android:maxLines="1" />
</LinearLayout>
```

<Tabs>
  <Tab title="Kotlin">
    ```kotlin SearchActivity.kt lines theme={null}
    binding.cometchatSearch.setTextMessageItemView(object : MessagesSearchViewHolderListener<TextMessage>() {
        override fun createView(
            context: Context?,
            listItem: View?
        ): View? {
            return layoutInflater.inflate(R.layout.custom_message_item_view, null)
        }

        override fun bindView(
            context: Context?,
            createdView: View?,
            message: TextMessage?,
            holder: RecyclerView.ViewHolder?,
            messagesList: List<BaseMessage?>?,
            position: Int
        ) {
            val titleTv = createdView?.findViewById<android.widget.TextView>(R.id.tv_sender_name)
            val messageTv = createdView?.findViewById<android.widget.TextView>(R.id.tv_message)

            titleTv?.text = message?.sender?.name
            messageTv?.text = message?.text
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java SearchActivity.java lines theme={null}
    binding.cometchatSearch.setTextMessageItemView(new MessagesSearchViewHolderListener<TextMessage>() {
        @Override
        public View createView(Context context, View listItem) {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            return layoutInflater.inflate(R.layout.custom_message_item_view, null);
        }

        @Override
        public void bindView(Context context, View createdView, TextMessage message, RecyclerView.ViewHolder holder, List<BaseMessage> messagesList, int position) {
            android.widget.TextView titleTv = createdView.findViewById(R.id.tv_sender_name);
            android.widget.TextView messageTv = createdView.findViewById(R.id.tv_message);

            if (message != null) {
                titleTv.setText(message.getSender().getName());
                messageTv.setText(message.getText());
            }
        }
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Registers a `MessagesSearchViewHolderListener` for text messages. The `createView` method inflates the custom layout, and `bindView` populates the sender name and message text from the `TextMessage` object.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-llms-scoped-indexes/zZz-wQk_4Cpgg3y_/images/android-custom-text-message-item.png?fit=max&auto=format&n=zZz-wQk_4Cpgg3y_&q=85&s=35a85ef3aff57de7f72d1afa85b8edb6" width="2560" height="1670" data-path="images/android-custom-text-message-item.png" />
</Frame>

### Other Message Item Views

The following message item view methods follow the same `MessagesSearchViewHolderListener` pattern as `setTextMessageItemView`:

| Method | Message Type | Generic Type |
| - | - | - |
| `setImageMessageItemView` | Image Message | `MessagesSearchViewHolderListener<MediaMessage>` |
| `setVideoMessageItemView` | Video Message | `MessagesSearchViewHolderListener<MediaMessage>` |
| `setAudioMessageItemView` | Audio Message | `MessagesSearchViewHolderListener<MediaMessage>` |
| `setDocumentMessageItemView` | Document Message | `MessagesSearchViewHolderListener<MediaMessage>` |
| `setLinkMessageItemView` | Link Message | `MessagesSearchViewHolderListener<TextMessage>` |

### `setInitialView`

Sets a custom view displayed when the search component is rendered and no search has been performed.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    binding.cometchatSearch.setInitialView(R.layout.your_initial_view)
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    binding.cometchatSearch.setInitialView(R.layout.your_initial_view);
    ```
  </Tab>
</Tabs>

### `setEmptyView`

Configures a custom view displayed when the search returns no results.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    binding.cometchatSearch.setEmptyView(R.layout.your_empty_view)
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    binding.cometchatSearch.setEmptyView(R.layout.your_empty_view);
    ```
  </Tab>
</Tabs>

### `setLoadingView`

Sets a custom loading view displayed when search results are being fetched.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    binding.cometchatSearch.setLoadingView(loadingView)
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    binding.cometchatSearch.setLoadingView(loadingView);
    ```
  </Tab>
</Tabs>

### `setErrorView`

Defines a custom error state view that appears when an issue occurs while searching.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    binding.cometchatSearch.setErrorView(errorView)
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    binding.cometchatSearch.setErrorView(errorView);
    ```
  </Tab>
</Tabs>

* **Verify**: After setting any custom view slot, confirm the custom view renders in the correct position within the search result items, and the data binding populates correctly for each result.

## Common Patterns

### Messages-only search

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    binding.cometchatSearch.setSearchFilters(
        listOf(UIKitConstants.SearchFilter.MESSAGES)
    )
    binding.cometchatSearch.setInitialSearchFilter(UIKitConstants.SearchFilter.MESSAGES)
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    binding.cometchatSearch.setSearchFilters(
        Arrays.asList(UIKitConstants.SearchFilter.MESSAGES)
    );
    binding.cometchatSearch.setInitialSearchFilter(UIKitConstants.SearchFilter.MESSAGES);
    ```
  </Tab>
</Tabs>

### Filter by message type

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    binding.cometchatSearch.setMessagesRequestBuilder(
        MessagesRequest.MessagesRequestBuilder().setLimit(10)
    )
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    binding.cometchatSearch.setMessagesRequestBuilder(
        new MessagesRequest.MessagesRequestBuilder().setLimit(10)
    );
    ```
  </Tab>
</Tabs>

### Scope search to a specific user

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    binding.cometchatSearch.setUid("user123")
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    binding.cometchatSearch.setUid("user123");
    ```
  </Tab>
</Tabs>

### Scope search to a specific group

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    binding.cometchatSearch.setGuid("group123")
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    binding.cometchatSearch.setGuid("group123");
    ```
  </Tab>
</Tabs>

## Advanced Methods

### Search Scope

#### `setUid`

Scopes the search to a specific user's conversation.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    binding.cometchatSearch.setUid("user123")
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    binding.cometchatSearch.setUid("user123");
    ```
  </Tab>
</Tabs>

#### `setGuid`

Scopes the search to a specific group's conversation.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    binding.cometchatSearch.setGuid("group123")
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    binding.cometchatSearch.setGuid("group123");
    ```
  </Tab>
</Tabs>

### Request Builders

#### `setConversationsRequestBuilder`

Sets a `ConversationsRequest.ConversationsRequestBuilder` to filter conversation search results. Pass the builder instance — not the result of `.build()`. For all available builder options, refer to the [ConversationRequestBuilder](/sdk/android/retrieve-conversations) documentation.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    binding.cometchatSearch.setConversationsRequestBuilder(
        ConversationsRequest.ConversationsRequestBuilder().setLimit(10)
    )
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    binding.cometchatSearch.setConversationsRequestBuilder(
        new ConversationsRequest.ConversationsRequestBuilder().setLimit(10)
    );
    ```
  </Tab>
</Tabs>

#### `setMessagesRequestBuilder`

Sets a `MessagesRequest.MessagesRequestBuilder` to filter message search results. For all available builder options, refer to the [MessagesRequestBuilder](/sdk/android/additional-message-filtering) documentation.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    binding.cometchatSearch.setMessagesRequestBuilder(
        MessagesRequest.MessagesRequestBuilder().setLimit(5)
    )
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    binding.cometchatSearch.setMessagesRequestBuilder(
        new MessagesRequest.MessagesRequestBuilder().setLimit(5)
    );
    ```
  </Tab>
</Tabs>

### Text Formatters

#### `setTextFormatters`

Enables developers to define and apply text formatters that dynamically modify or transform message content before rendering it in the UI. Text formatters can be used for:

* Automatically converting URLs into clickable links
* Applying Markdown or rich text styling
* Replacing certain words or patterns with emojis or predefined text
* Censoring specific words for moderation

For implementation details, refer to the [MentionsFormatter Guide](/ui-kit/android/v5/mentions-formatter-guide).

### Date/Time Formatting

#### `setDateTimeFormatter`

Provides a custom implementation of `DateTimeFormatterCallback` to configure how time and date values are displayed in search results.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    import java.text.SimpleDateFormat
    import java.util.*

    binding.cometchatSearch.setDateTimeFormatter(object : DateTimeFormatterCallback {

        private val fullTimeFormatter = SimpleDateFormat("hh:mm a", Locale.getDefault())
        private val dateFormatter = SimpleDateFormat("dd MMM yyyy", Locale.getDefault())

        override fun time(timestamp: Long): String {
            return fullTimeFormatter.format(Date(timestamp))
        }

        override fun today(timestamp: Long): String {
            return "Today"
        }

        override fun yesterday(timestamp: Long): String {
            return "Yesterday"
        }

        override fun lastWeek(timestamp: Long): String {
            return "Last Week"
        }

        override fun otherDays(timestamp: Long): String {
            return dateFormatter.format(Date(timestamp))
        }

        override fun minutes(diffInMinutesFromNow: Long, timestamp: Long): String {
            return "$diffInMinutesFromNow mins ago"
        }

        override fun hours(diffInHourFromNow: Long, timestamp: Long): String {
            return "$diffInHourFromNow hrs ago"
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;

    binding.cometchatSearch.setDateTimeFormatter(new DateTimeFormatterCallback() {

        private final SimpleDateFormat fullTimeFormatter = new SimpleDateFormat("hh:mm a", Locale.getDefault());
        private final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy", Locale.getDefault());

        @Override
        public String time(long timestamp) {
            return fullTimeFormatter.format(new Date(timestamp));
        }

        @Override
        public String today(long timestamp) {
            return "Today";
        }

        @Override
        public String yesterday(long timestamp) {
            return "Yesterday";
        }

        @Override
        public String lastWeek(long timestamp) {
            return "Last Week";
        }

        @Override
        public String otherDays(long timestamp) {
            return dateFormatter.format(new Date(timestamp));
        }

        @Override
        public String minutes(long diffInMinutesFromNow, long timestamp) {
            return diffInMinutesFromNow + " mins ago";
        }

        @Override
        public String hours(long diffInHourFromNow, long timestamp) {
            return diffInHourFromNow + " hrs ago";
        }
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Provides a custom date/time formatter that displays "Today", "Yesterday", "Last Week" for recent messages, a "dd MMM yyyy" format for older messages, and relative time strings like "5 mins ago" or "2 hrs ago" for recent activity.

### Other Advanced Methods

| Method | Type | Description |
| - | - | - |
| `setMentionAllLabelId` | `String id, String mentionAllLabel` | Sets a custom label for the "mention all" feature for a specific ID |
| `setHintText` | `String` | Sets the hint text displayed in the search bar |

## Style

The component uses XML theme styles. Define a custom style with parent `CometChatSearchStyle` in `themes.xml`, then apply with `setStyle()`.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-llms-scoped-indexes/zZz-wQk_4Cpgg3y_/images/android-search-style.png?fit=max&auto=format&n=zZz-wQk_4Cpgg3y_&q=85&s=adcae0781906470ae42c080c949f90eb" width="2560" height="1670" data-path="images/android-search-style.png" />
</Frame>

```xml themes.xml lines theme={null}
    <style name="CustomSearchStyle" parent="CometChatSearchStyle">
        <item name="cometchatSearchBackgroundColor">#EDEAFA</item>

        <item name="cometchatSearchFilterChipTextAppearance">@style/textStyleTimesNewRoman</item>

        <item name="cometchatSearchSectionHeaderTextAppearance">@style/textStyleTimesNewRoman</item>
        <item name="cometchatSearchSectionHeaderBackgroundColor">#EDEAFA</item>

        <item name="cometchatSearchConversationItemBackgroundColor">#EDEAFA</item>
        <item name="cometchatSearchConversationSubtitleTextAppearance">@style/textStyleTimesNewRoman</item>
        <item name="cometchatSearchConversationTitleTextAppearance">@style/textStyleTimesNewRoman</item>
        <item name="cometchatSearchConversationTimestampTextAppearance">?attr/cometchatTextAppearanceCaption1Bold</item>

        <item name="cometchatSearchSeeMoreTextAppearance">@style/textStyleTimesNewRoman</item>

        <item name="cometchatSearchMessageItemBackgroundColor">#EDEAFA</item>
        <item name="cometchatSearchMessageTitleTextAppearance">@style/textStyleTimesNewRoman</item>
        <item name="cometchatSearchMessageSubtitleTextAppearance">@style/textStyleTimesNewRoman</item>
        <item name="cometchatSearchMessageTimestampTextAppearance">@style/textStyleTimesNewRoman</item>

        <item name="cometchatSearchBarTextAppearance">@style/textStyleTimesNewRoman</item>
    </style>

    <style name="textStyleTimesNewRoman">
        <item name="android:fontFamily">@font/times_new_roman_regular</item>
    </style>
```

> **What this does:** Defines a custom search style that sets a light purple background color (`#EDEAFA`) for the search component, conversation items, and message items, and applies a Times New Roman font to all text elements including filter chips, section headers, conversation titles/subtitles, message titles/subtitles, timestamps, "see more" text, and the search bar.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    binding.cometchatSearch.setStyle(R.style.CustomSearchStyle)
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    binding.cometchatSearch.setStyle(R.style.CustomSearchStyle);
    ```
  </Tab>
</Tabs>

To view all available style attributes, visit the [attributes file](https://github.com/cometchat/cometchat-uikit-android/blob/v5/chatuikit/src/main/res/values/attr_cometchat_search.xml).

### Programmatic Style Properties

In addition to XML theme styles, the component exposes programmatic setters for fine-grained control:

**Search Bar**

| Method | Type | Description |
| - | - | - |
| `setBackgroundColor` | `@ColorInt int` | Background color of the component |
| `setSearchBarBackgroundColor` | `@ColorInt int` | Background color of the search bar |
| `setSearchBarStrokeWidth` | `@Dimension int` | Stroke width of the search bar border |
| `setSearchBarStrokeColor` | `@ColorInt int` | Stroke color of the search bar border |
| `setSearchBarCornerRadius` | `@Dimension int` | Corner radius of the search bar |
| `setSearchBarTextColor` | `@ColorInt int` | Text color of the search bar input |
| `setSearchBarTextAppearance` | `@StyleRes int` | Text appearance of the search bar input |
| `setSearchBarHintTextColor` | `@ColorInt int` | Hint text color of the search bar |
| `setBackIcon` | `Drawable` | Custom back icon drawable |
| `setBackIconTint` | `@ColorInt int` | Tint color for the back icon |
| `setClearIcon` | `Drawable` | Custom clear icon drawable |
| `setClearIconTint` | `@ColorInt int` | Tint color for the clear icon |
| `setSearchIcon` | `Drawable` | Custom search icon drawable |
| `setSearchIconTint` | `@ColorInt int` | Tint color for the search icon |

**Filter Chips**

| Method | Type | Description |
| - | - | - |
| `setFilterChipBackgroundColor` | `@ColorInt int` | Background color of filter chips |
| `setFilterChipSelectedBackgroundColor` | `@ColorInt int` | Background color of selected filter chips |
| `setFilterChipTextColor` | `@ColorInt int` | Text color of filter chips |
| `setFilterChipSelectedTextColor` | `@ColorInt int` | Text color of selected filter chips |
| `setFilterChipTextAppearance` | `@StyleRes int` | Text appearance of filter chips |
| `setFilterChipStrokeColor` | `@ColorInt int` | Stroke color of filter chips |
| `setFilterChipSelectedStrokeColor` | `@ColorInt int` | Stroke color of selected filter chips |
| `setFilterChipStrokeWidth` | `@Dimension int` | Stroke width of filter chips |
| `setFilterChipCornerRadius` | `@Dimension int` | Corner radius of filter chips |

**Section Headers**

| Method | Type | Description |
| - | - | - |
| `setSectionHeaderTextColor` | `@ColorInt int` | Text color for section headers |
| `setSectionHeaderTextAppearance` | `@StyleRes int` | Text appearance for section headers |
| `setSectionHeaderBackgroundColor` | `@ColorInt int` | Background color for section headers |

**Conversation Items**

| Method | Type | Description |
| - | - | - |
| `setConversationItemBackgroundColor` | `@ColorInt int` | Background color for conversation items |
| `setConversationTitleTextColor` | `@ColorInt int` | Text color for conversation titles |
| `setConversationTitleTextAppearance` | `@StyleRes int` | Text appearance for conversation titles |
| `setConversationSubtitleTextColor` | `@ColorInt int` | Text color for conversation subtitles |
| `setConversationSubtitleTextAppearance` | `@StyleRes int` | Text appearance for conversation subtitles |
| `setConversationTimestampTextColor` | `@ColorInt int` | Text color for conversation timestamps |
| `setConversationTimestampTextAppearance` | `@StyleRes int` | Text appearance for conversation timestamps |

**Message Items**

| Method | Type | Description |
| - | - | - |
| `setMessageItemBackgroundColor` | `@ColorInt int` | Background color for message items |
| `setMessageTitleTextColor` | `@ColorInt int` | Text color for message titles |
| `setMessageTitleTextAppearance` | `@StyleRes int` | Text appearance for message titles |
| `setMessageSubtitleTextColor` | `@ColorInt int` | Text color for message subtitles |
| `setMessageSubtitleTextAppearance` | `@StyleRes int` | Text appearance for message subtitles |
| `setMessageTimestampTextColor` | `@ColorInt int` | Text color for message timestamps |
| `setMessageTimestampTextAppearance` | `@StyleRes int` | Text appearance for message timestamps |
| `setMessageLinkTextColor` | `@ColorInt int` | Text color for links in messages |
| `setMessageLinkTextAppearance` | `@StyleRes int` | Text appearance for links in messages |

**Other Style Properties**

| Method | Type | Description |
| - | - | - |
| `setAvatarStyle` | `@StyleRes int` | Style for avatars in search results |
| `setBadgeStyle` | `@StyleRes int` | Style for badges in search results |
| `setSeeMoreTextColor` | `@ColorInt int` | Text color for "See more" links |
| `setSeeMoreTextAppearance` | `@StyleRes int` | Text appearance for "See more" links |
| `setDateSeparatorTextColor` | `@ColorInt int` | Text color for date separators |
| `setDateSeparatorBackgroundColor` | `@ColorInt int` | Background color for date separators |
| `setDateSeparatorTextAppearance` | `@StyleRes int` | Text appearance for date separators |
| `setEmptyStateTextColor` | `@ColorInt int` | Title text color for the empty state |
| `setEmptyStateTextAppearance` | `@StyleRes int` | Title text appearance for the empty state |
| `setEmptyStateSubtitleTextColor` | `@ColorInt int` | Subtitle text color for the empty state |
| `setEmptyStateSubtitleTextAppearance` | `@StyleRes int` | Subtitle text appearance for the empty state |
| `setEmptyStateIcon` | `Drawable` | Icon for the empty state |
| `setEmptyStateIconTint` | `@ColorInt int` | Tint for the empty state icon |
| `setErrorStateTextColor` | `@ColorInt int` | Title text color for the error state |
| `setErrorStateTextAppearance` | `@StyleRes int` | Title text appearance for the error state |
| `setErrorStateSubtitleTextColor` | `@ColorInt int` | Subtitle text color for the error state |
| `setErrorStateSubtitleTextAppearance` | `@StyleRes int` | Subtitle text appearance for the error state |
| `setErrorStateIcon` | `Drawable` | Icon for the error state |
| `setErrorStateIconTint` | `@ColorInt int` | Tint for the error state icon |

## Customization Matrix

| What to change | Where | Property/API | Example |
| - | - | - | - |
| Override behavior on conversation tap | Activity/Fragment | `setOnConversationClicked` | `setOnConversationClicked { v, pos, conv -> ... }` |
| Override behavior on message tap | Activity/Fragment | `setOnMessageClicked` | `setOnMessageClicked { v, pos, msg -> ... }` |
| Override back press behavior | Activity/Fragment | `setOnBackPressListener` | `setOnBackPressListener { ... }` |
| Scope search to a user | Activity/Fragment | `setUid(String)` | `.setUid("user123")` |
| Scope search to a group | Activity/Fragment | `setGuid(String)` | `.setGuid("group123")` |
| Hide user online status | Activity/Fragment | `setHideUserStatus(boolean)` | `.setHideUserStatus(true)` |
| Hide group type icon | Activity/Fragment | `setHideGroupType(boolean)` | `.setHideGroupType(true)` |
| Set search filters | Activity/Fragment | `setSearchFilters(List)` | `.setSearchFilters(filters)` |
| Set initial active filter | Activity/Fragment | `setInitialSearchFilter(SearchFilter)` | `.setInitialSearchFilter(UIKitConstants.SearchFilter.MESSAGES)` |
| Set search scope | Activity/Fragment | `setSearchIn(List<SearchScope>)` | `.setSearchIn(scopes)` |
| Filter conversation results | Activity/Fragment | `setConversationsRequestBuilder` | See Request Builders code above |
| Filter message results | Activity/Fragment | `setMessagesRequestBuilder` | See Request Builders code above |
| Custom conversation item view | Activity/Fragment | `setConversationItemView(ConversationsSearchViewHolderListener)` | See `setConversationItemView` code above |
| Custom text message item view | Activity/Fragment | `setTextMessageItemView(MessagesSearchViewHolderListener)` | See `setTextMessageItemView` code above |
| Custom image message item view | Activity/Fragment | `setImageMessageItemView(MessagesSearchViewHolderListener)` | See `setTextMessageItemView` pattern |
| Custom video message item view | Activity/Fragment | `setVideoMessageItemView(MessagesSearchViewHolderListener)` | See `setTextMessageItemView` pattern |
| Custom audio message item view | Activity/Fragment | `setAudioMessageItemView(MessagesSearchViewHolderListener)` | See `setTextMessageItemView` pattern |
| Custom document message item view | Activity/Fragment | `setDocumentMessageItemView(MessagesSearchViewHolderListener)` | See `setTextMessageItemView` pattern |
| Custom link message item view | Activity/Fragment | `setLinkMessageItemView(MessagesSearchViewHolderListener)` | See `setTextMessageItemView` pattern |
| Custom initial view | Activity/Fragment | `setInitialView(@LayoutRes int)` | `.setInitialView(R.layout.your_initial_view)` |
| Custom loading view | Activity/Fragment | `setLoadingView(View)` | `.setLoadingView(loadingView)` |
| Custom empty view | Activity/Fragment | `setEmptyView(@LayoutRes int)` | `.setEmptyView(R.layout.your_empty_view)` |
| Custom error view | Activity/Fragment | `setErrorView(View)` | `.setErrorView(errorView)` |
| Empty state visibility | Activity/Fragment | `setEmptyStateVisibility(int)` | `.setEmptyStateVisibility(View.GONE)` |
| Error state visibility | Activity/Fragment | `setErrorStateVisibility(int)` | `.setErrorStateVisibility(View.GONE)` |
| Change colors, fonts, spacing | `themes.xml` | `CometChatSearchStyle` | `<item name="cometchatSearchBackgroundColor">#EDEAFA</item>` |
| Apply a custom style | Activity/Fragment | `setStyle(int styleRes)` | `binding.cometchatSearch.setStyle(R.style.CustomSearchStyle)` |
| Search bar background | Activity/Fragment | `setSearchBarBackgroundColor` | `.setSearchBarBackgroundColor(color)` |
| Filter chip colors | Activity/Fragment | `setFilterChip*` methods | `.setFilterChipBackgroundColor(color)` |
| Section header style | Activity/Fragment | `setSectionHeader*` methods | `.setSectionHeaderTextColor(color)` |
| Conversation item style | Activity/Fragment | `setConversation*` methods | `.setConversationTitleTextColor(color)` |
| Message item style | Activity/Fragment | `setMessage*` methods | `.setMessageTitleTextColor(color)` |
| Date/time formatting | Activity/Fragment | `setDateTimeFormatter(DateTimeFormatterCallback)` | See `setDateTimeFormatter` code above |
| Text formatters | Activity/Fragment | `setTextFormatters(List)` | See Text Formatters section |
| Search bar hint text | Activity/Fragment | `setHintText(String)` | `.setHintText("Search...")` |
| Mention-all label | Activity/Fragment | `setMentionAllLabelId(String, String)` | `.setMentionAllLabelId(id, label)` |
| Callback on messages loaded | Activity/Fragment | `setOnLoadMessages(OnLoad<BaseMessage>)` | `.setOnLoadMessages { list -> ... }` |
| Callback on conversations loaded | Activity/Fragment | `setOnLoadConversations(OnLoad<Conversation>)` | `.setOnLoadConversations { list -> ... }` |

## Next Steps

<CardGroup cols={2}>
  <Card title="Conversations" icon="comments" href="/ui-kit/android/v5/conversations">
    Browse recent conversations
  </Card>

  <Card title="Users" icon="user" href="/ui-kit/android/v5/users">
    Browse and search available users
  </Card>

  <Card title="Groups" icon="users" href="/ui-kit/android/v5/groups">
    Browse and search available groups
  </Card>

  <Card title="Message List" icon="messages" href="/ui-kit/android/v5/message-list">
    Display messages in a conversation
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.