custom searchview in toolbar android :
Step-1: Search Activity .Xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BuyerActivity.SearchActivity">
<androidx.cardview.widget.CardView
android:id="@+id/card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="3dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar2"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:contentInsetStart="0dp"
app:layout_scrollFlags="scroll|enterAlways"
android:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/search_icon"
android:layout_width="24dp"
android:layout_marginLeft="16dp"
android:layout_height="match_parent"
android:src="@drawable/search">
</ImageView>
<androidx.appcompat.widget.SearchView
android:id="@+id/search_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
app:defaultQueryHint=" Search Blog...."
app:iconifiedByDefault="false"
app:searchIcon="@null"
>
</androidx.appcompat.widget.SearchView>
<ImageView
android:id="@+id/mic_icon"
android:layout_width="24dp"
android:layout_marginRight="16dp"
android:layout_height="match_parent"
android:src="@drawable/mic">
</ImageView>
</LinearLayout>
</androidx.appcompat.widget.Toolbar>
</androidx.cardview.widget.CardView>
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="36dp"
android:layout_marginEnd="8dp"
android:visibility="gone"
android:text="Product not found"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/card" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step-2 : Search Activity.java code :
public class BlogSearchActivity extends BaseActivity {
private TextView textView;
private ImageView searchIcon;
public static SearchView searchView;
private ImageView micBtn;
public static final Integer RecordAudioRequestCode = 1;
private final int REQ_CODE_SPEECH_INPUT = 100;
@SuppressLint("ClickableViewAccessibility")
@Override
protected void initViews() {
searchView = findViewById(R.id.search_view);
textView = findViewById(R.id.textview);
searchIcon = findViewById(R.id.search_icon);
micBtn = findViewById(R.id.mic_icon);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.onActionViewExpanded();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
toHideKeyboard();
Search(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if(newText.equals("")){
micBtn.setVisibility(View.VISIBLE);
searchIcon.setVisibility(View.VISIBLE);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
searchView.setPadding(0,0,0,0);
}else {
searchView.setPadding(-16,0,0,0);
searchIcon.setVisibility(View.GONE);
micBtn.setVisibility(View.GONE);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
return false;
}
});
ImageView clearButton = searchView.findViewById(androidx.appcompat.R.id.search_close_btn);
clearButton.setOnClickListener(v -> {
if(searchView.getQuery().length() == 0) {
searchView.setIconified(true);
} else {
// Do your task here
searchView.setQuery("", false);
}
});
micBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(ContextCompat.checkSelfPermission(currentActivity,
Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){
checkPermission();
}else {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
}
});
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
searchView.setQuery(query, false);
}
}
private void Search(String query) {
Intent intent = new Intent(BlogSearchActivity.this, paas Activity which is appear after search .class);
intent.putExtra("query",query);
startActivity(intent);
}
@Override
protected void initContext() {
context = BlogSearchActivity.this;
currentActivity = BlogSearchActivity.this;
}
@Override
protected void initListners() {
}
@Override
protected boolean isActionBar() {
return true;
}
@Override
protected boolean isHomeButton() {
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_blog);
}
@Override
public void onClick(View view) {
}
@Override
public void onAlertClicked(int alertType) {
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
searchView.setQuery(result.get(0),false);
}
break;
}
}
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.RECORD_AUDIO},RecordAudioRequestCode);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == RecordAudioRequestCode && grantResults.length > 0 ){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
}
}
}