The following will create a SearchView identical to the one in Gmail and add it to the given Toolbar. You'll just have to implement your own "ViewUtil.convertDpToPixel" method.
private SearchView createMaterialSearchView(Toolbar toolbar, String hintText) {
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
SearchView searchView = new SearchView(this);
searchView.setIconifiedByDefault(false);
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setMinimumHeight(Integer.MAX_VALUE);
searchView.setQueryHint(hintText);
int rightMarginFrame = 0;
View frame = searchView.findViewById(getResources().getIdentifier("android:id/search_edit_frame", null, null));
if (frame != null) {
LinearLayout.LayoutParams frameParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
rightMarginFrame = ((LinearLayout.LayoutParams) frame.getLayoutParams()).rightMargin;
frameParams.setMargins(0, 0, 0, 0);
frame.setLayoutParams(frameParams);
}
View plate = searchView.findViewById(getResources().getIdentifier("android:id/search_plate", null, null));
if (plate != null) {
plate.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
plate.setPadding(0, 0, rightMarginFrame, 0);
plate.setBackgroundColor(Color.TRANSPARENT);
}
int autoCompleteId = getResources().getIdentifier("android:id/search_src_text", null, null);
if (searchView.findViewById(autoCompleteId) != null) {
EditText autoComplete = (EditText) searchView.findViewById(autoCompleteId);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, (int) ViewUtil.convertDpToPixel(36));
params.weight = 1;
params.gravity = Gravity.CENTER_VERTICAL;
params.leftMargin = rightMarginFrame;
autoComplete.setLayoutParams(params);
autoComplete.setTextSize(16f);
}
int searchMagId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
if (searchView.findViewById(searchMagId) != null) {
ImageView v = (ImageView) searchView.findViewById(searchMagId);
v.setImageDrawable(null);
v.setPadding(0, 0, 0, 0);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 0, 0);
v.setLayoutParams(params);
}
toolbar.setTitle(null);
toolbar.setContentInsetsAbsolute(0, 0);
toolbar.addView(searchView);
return searchView;
}