2

I am trying to imitate the style of how search is handled by the gmail app which looks as follows:

enter image description here

As shown above there is a (blue) blinking cursor after the search query in the searchView.

My respective code looks like this:

SearchReslutActivity.class

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setQuery(getIntent().getStringExtra(SearchManager.QUERY), false);
    searchView.setIconified(false);
    searchView.clearFocus();

    return true;
}

menu/search_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/search"
    android:title="@string/search_title"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="always" /> </menu>

xml/searchable.xml

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="@string/hint"
android:includeInGlobalSearch="true"
android:inputType="textCapWords"
android:label="@string/app_name"
android:searchSuggestAuthority="com.webaddress.myproject.data.Provider"
android:searchSuggestIntentAction="android.intent.action.VIEW"
android:searchSuggestIntentData="content://com.webaddress.myproject.data.Provider/table"
android:searchSuggestSelection=" ?"
android:searchSuggestThreshold="1" />

The above code achieves the same look as what is displayed in the gmail app except for having a blinking cursor. How can I add such a blinking cursor without requesting focus on the searchView (which in turn will make the soft keyboard pop up again)?

Thanks!

Jonathan Rhein
  • 1,616
  • 3
  • 23
  • 47
  • Possible duplicate of [Android Hide Soft Keyboard from EditText while not losing cursor](http://stackoverflow.com/questions/13586354/android-hide-soft-keyboard-from-edittext-while-not-losing-cursor) – Zahid Rasheed Mar 23 '17 at 08:53
  • I tracked the sources. Problem comes from [this](http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4_r1/android/support/v7/widget/SearchView.java#1696) line: `mSearchView.clearFocus();` . If this was commented out blinking would work imo. – azizbekian Mar 23 '17 at 10:19
  • Yes, but when I comment out `mSearchView.clearFocus();` the keyboard will pop up again... – Jonathan Rhein Mar 23 '17 at 10:23
  • @Joni, I was not talking about commenting out in your code. In the `SearchView` class that the link points to. – azizbekian Mar 23 '17 at 10:42
  • ah, my mistake! – Jonathan Rhein Mar 23 '17 at 10:45

5 Answers5

2

Add this code in onCreate()

searchView.setOnFocusChangeListener(new View.OnFocusChangeListener() {

      @Override
      public void onFocusChange(View v, boolean hasFocus) {

          if (!searchView.hasFocus()) {
              //this if condition is true when searchview lost focus...
              int searchSrcText = searchView.getContext().getResources()
                  .getIdentifier("android:id/search_src_text", null, null);
              EditText editText = (EditText) searchView.findViewById(searchSrcText);
              editText.setCursorVisible(true);
              searchView.setActivated(true);
              searchView.setPressed(true);
          }
      }
});
JJD
  • 50,076
  • 60
  • 203
  • 339
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
  • 1
    Still not blinking. Running on API 21 with `android.support.v7.widget.SearchView` from `25.3.0`. – azizbekian Mar 23 '17 at 09:44
  • Yes, same for me. If I place the code into my `onCreate()` my app will crash. If I place it within my `onCreateOptionsMenu()` nothing happens, i.e. when I call `searchView.clearFocus()` the `onFocusChange()` is not even entered. What am I doing wrong? I have added my respective xml files, hopefully my mistake becomes clearer now. – Jonathan Rhein Mar 23 '17 at 10:17
1

Thanks to @Azizbekian's answer (which did not work on its own for me) I finally got it working with the following code (in an empty project - support libs 25.3.0):

java/MainActivity

package com.yourwebpage.yourapplication;

import android.app.SearchManager;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        getMenuInflater().inflate(R.menu.search_menu, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(final Menu menu) {
        MenuItem menuItem = menu.findItem(R.id.search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        searchView.setQuery(getIntent().getStringExtra(SearchManager.QUERY), false);
        searchView.setIconified(false);
        SearchView.SearchAutoComplete searchAutoComplete =
                (SearchView.SearchAutoComplete) searchView.findViewById(R.id.search_src_text);
        searchAutoComplete.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(final View v, final boolean hasFocus) {
                v.requestFocus();
            }
        });
        searchView.clearFocus();
        return super.onPrepareOptionsMenu(menu);
    }
}

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.yourwebpage.yourapplication.MainActivity">
</android.support.constraint.ConstraintLayout>

res/menu/search_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/search"
        android:title="Search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="always"/>
</menu>

manifests/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yourwebpage.yourapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:windowSoftInputMode="stateAlwaysHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I am posting this rather comprehensive solution in the hope of making it reproducible thereby.

Jonathan Rhein
  • 1,616
  • 3
  • 23
  • 47
0

Try this,

    searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
             searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        }
    });
Komal12
  • 3,340
  • 4
  • 16
  • 25
0

Perform this:

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    getMenuInflater().inflate(R.menu.search_menu, menu);
    return true;
}

@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
    MenuItem menuItem = menu.findItem(R.id.search);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
    SearchView.SearchAutoComplete searchAutoComplete = 
        (SearchView.SearchAutoComplete) searchView.findViewById(R.id.search_src_text);
    searchAutoComplete.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(final View v, final boolean hasFocus) {
            v.requestFocus();
        }
    });
    return super.onPrepareOptionsMenu(menu);
}

search_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
            android:id="@+id/search"
            android:title="Search"
            app:actionViewClass="android.support.v7.widget.SearchView"
            app:showAsAction="ifRoom"/>

</menu>

Tested with support libs version 25.3.0.

Result

azizbekian
  • 60,783
  • 13
  • 169
  • 249
  • Thanks! When I insert your code into mine there is indeed a blinking cursor BUT there is also the keyboard popping up again... maybe I am doing something wrong when merging your code snippet with my existing code base. Could you maybe update your answer showing what my entire `onCreateOptionsMenu()` should look like in the end? – Jonathan Rhein Mar 23 '17 at 10:43
  • ok, and where goes all my code with regard to the `searchableInfo` (the initialisation of `SearchManager` and the `setSearchableInfo`) and my call to show the search query within the `SearchView` (as previously accomplished by `setQuery()`)? – Jonathan Rhein Mar 23 '17 at 11:24
  • `onPrepareOptionsMenu()` is the callback, where you should setup your menu. – azizbekian Mar 23 '17 at 11:25
  • Yeah that is what I did (inserting my code from `onCreateOptionsMenu()` right after your code in the `onPrepareOptionsMenu()`), but then the keyboard pops up again... sorry for keeping you busy, it is probably something small I am missing. – Jonathan Rhein Mar 23 '17 at 11:32
  • I've posted all the code you need, it's basically an empty project. Search for the problem on your side. You may create an empty project from scratch and check how it behaves. – azizbekian Mar 23 '17 at 11:33
0

This code is for custom toolbar

 SearchView.SearchAutoComplete searchTextView =  mSearchView.findViewById(R.id.search_src_text);
        try {
            Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
            mCursorDrawableRes.setAccessible(true);
            mCursorDrawableRes.set(searchTextView, 0);
            //This sets the cursor resource ID to 0 or @null which will make it visible on white background
        } catch (Exception e) {
            e.printStackTrace();
        }
Pawan Chaurasiya
  • 881
  • 2
  • 16
  • 30