Searchview in Centre and After Focus It Goes to App Bar in Android

Searchview focus to move from center to toolbar Android

To achieve something similar to the gif that you attached , you can try this :

In your activity_main.xml layout file :

<androidx.coordinatorlayout.widget.CoordinatorLayout 
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"
android:focusable="true">

<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appBar"
android:layout_width="match_parent"
android:gravity="bottom"
android:backgroundTint="@color/red_primary_80"
android:layout_height="?attr/collapsingToolbarLayoutLargeSize"
android:fitsSystemWindows="true">

<androidx.appcompat.widget.SearchView
android:id="@+id/searchView"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_marginStart="16dp"
app:iconifiedByDefault="false"
android:layout_marginEnd="16dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed|snap"
/>

</com.google.android.material.appbar.AppBarLayout>

<!-- Scrollable content -->

</androidx.coordinatorlayout.widget.CoordinatorLayout>

In your MainActivity.java file :

public class MainActivity extends Activity {

private TextInputEditText txt;
private AppBarLayout appBarLayout;

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

txt = findViewById(R.id.textField);
appBarLayout = findViewById(R.id.appBar);

//This code will collapse the AppBar according to the focus on the textField
txt.setOnFocusChangeListener((v, hasFocus) -> {
appBarLayout.setExpanded(!hasFocus);
});
}

// Function to clear focus from the textfield when you touch outside the view

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (v instanceof SearchView.SearchAutoComplete) {
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent( event );
}
}

You can modify the layout further to achieve your desired look.

Android appcompat toolbar stretches when searchview gets focus

Ok, I figured it out. There was no problem with the SearchView, because the same happened with ordinary EditTexts which were placed normally inside a layout xml. The Toolbar wasn't the problem either.

I created an empty activity and played around with anything I changed in my app and finally came to my theme. On KitKat and later I had <item name="android:windowTranslucentStatus">true</item> set on the theme, so the navigation drawer would appear behind the status bar.

Disabling/removing this would resolve the issue. This reminded me of the android:fitsSystemWindows="true" property. It is set on the Toolbar, but not in the layout xml of the main activity that contains the DrawerLayout.
I guess the DrawerLayout sets itself to fit the system windows.
E.g. there's no fitSystemWindows property here:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DashboardActivity">

The activity where the problem occurred did not have a NavigationDrawer, it was a new activity. Setting android:fitsSystemWindows="true" on the root node of the layout of the activity made things work fine.

So, for anyone to read this: if you have <item name="android:windowTranslucentStatus">true</item> in your theme, make sure any root node containing a toolbar contains a android:fitsSystemWindows="true".

Working sample:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">

<include layout="@layout/toolbar" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button" />
</LinearLayout>
</LinearLayout>

Expand and give focus to SearchView automatically

To make the SearchView expanded by default, call setIconifiedByDefault(false) on it when you initialise it (e.g. in onCreateOptionsMenu(..) or onPrepareOptionsMenu(..)). I've found in most cases this will give it focus automatically, but if not simply call requestFocus() on it too.

How to use Appbar with toolbar in android

You could change the start margin of the SearchView when it got the focus; and return it to the original margin when it loses the focus:

var originalMargin = 0
fun setupSearchView() {
binding.consultationSearchView.apply {
setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?) = false
override fun onQueryTextChange(newText: String?): Boolean {
if (newText != null) {
}
return true
}
})

val params =
binding.consultationSearchView.layoutParams as CollapsingToolbarLayout.LayoutParams
originalMargin = params.marginStart

setOnQueryTextFocusChangeListener { view, hasFocus ->
binding.appBar.setExpanded(!hasFocus)
isSelected = hasFocus

if (hasFocus)
params.marginStart = originalMargin + 150 // arbitrary constant
else
params.marginStart = originalMargin
view.layoutParams = params

}
}
}

Sample Image

Searchview overlaps custom title in toolbar. How to prevent?

I think you have 2 options,

Set width to SearchView in styles

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="searchViewStyle">@style/MySearchViewStyle</item>
</style>

<style name="MySearchViewStyle" parent="Widget.AppCompat.SearchView">
<item name="android:maxWidth">140dp</item>
</style>

Second option is get SeachView instance in onCreateOptionsMenu and calculate width of your toolbar_title layout set remaining width to search bar.

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setMaxWidth(calculatedWidth);
return super.onCreateOptionsMenu(menu);
}

But as per android standards, Search View has to extend completely in toolbar.
For this we have to use searchView.setMaxWidth(Integer.MAX_VALUE);.

Android search view not behaving right on toolbar

First declare a state variable to determine when menu item(s) needs to be hidden

boolean isHideMenuState = false;

Then reference the item(s) needed to be hidden inside onCreateOptionsMenu block

MenuItem logoutItem = menu.findItem(R.id.logout_btn);
//... initialize other menu items here

//use hidden state to define when to hide item(s)
if(isHideMenuState){
logoutItem.setVisible(false);
//by now the ellipses(...) should go off
//if not try using setShowAsAction passing (SHOW_AS_ACTION_NEVER)
}
else{
logoutItem.setVisible(true);
}

Next: Add focus change listener to your searchView

searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { 
@Override
public void onFocusChange(View v, boolean hasFocus) {
// Toggle isHideMenuState when search widget has focus/no focus
isHideMenuState = hasFocus
//Tell menu to re-create itself
invalidateOptionsMenu(); // onCreateOptionsMenu(...) is called again
}
});

And lastly for the UI try changing the actionViewClass of your searchView item

 app:actionViewClass="android.support.v7.widget.SearchView"

Push icons away when expandig searchview in android toolbar

Use ifRoom|collapseActionView for the attribute showAsAction

<item
android:id="@+id/action_search"
android:title="search"
app:actionViewClass="android.support.v7.widget.SearchView"
android:icon="@drawable/ic_search"
app:showAsAction="ifRoom|collapseActionView"/>


Related Topics



Leave a reply



Submit