Here is the simple complete solution in kotlin.
This whole layout will be your search bar
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_margin="10dp"
android:background="@drawable/your_desired_drawable">
<EditText
android:id="@+id/search_et"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_toStartOf="@id/clear_btn"
android:background="@null"
android:hint="search..."
android:imeOptions="actionSearch"
android:inputType="text"
android:maxLines="1"
android:paddingStart="15dp"
android:paddingEnd="10dp" />
<ImageView
android:id="@+id/clear_btn"
android:layout_width="20dp"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"
android:layout_marginEnd="15dp"
android:visibility="gone"
android:src="@drawable/ic_baseline_clear_24"/>
</RelativeLayout>
Now this is the functionality of clear button, paste this code in onCreate method.
search_et.addTextChangedListener(object: TextWatcher {
override fun beforeTextChanged(s:CharSequence, start:Int, count:Int, after:Int) {
}
override fun onTextChanged(s:CharSequence, start:Int, before:Int, count:Int) {
}
override fun afterTextChanged(s: Editable) {
if (s.isNotEmpty()){
clear_btn.visibility = VISIBLE
clear_btn.setOnClickListener {
search_et.text.clear()
}
}else{
clear_btn.visibility = GONE
}
}
})