2

I have been working on Implementing Custom search in Android App-bar. So, I have added following code in menu_main.xml

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

Now when I am looking at HomeActivity. It's look like this:

enter image description here

It's perfectly fine!. I haven't implemented the backend code for above SearchView. Now, I want to add some following features in above Search bar

  • User can search with tags (Searching with tags means that if there is a space between two words then I will treat them as tags). It's very similar to Pintreset app.

  • Further I want to get these tags from Search Bar and put into Get request parameter.

    Screenshot

enter image description here

Questions

  • For now, forgot about the Style. I just want to know How can I achieve this in my Search Bar?
  • How can I add box on every tag with this cross sign in Android app bar?

Any help would be appreciable.

Edit-1

I am adding onCreateOptionsMenu method:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
            .getActionView();
    if (null != searchView) {
        searchView.setSearchableInfo(searchManager
                .getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false);
    }

    SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
        public boolean onQueryTextChange(String newText) {
            // this is your adapter that will be filtered
            return true;
        }

        public boolean onQueryTextSubmit(String query) {
            //Here u can get the value "query" which is entered in the search box.
            return  true;
        }
    };
    searchView.setOnQueryTextListener(queryTextListener);

    return super.onCreateOptionsMenu(menu);
}

I am getting the submitting text in onCreateOptionsMenu.onQueryTextSubmit method. What should I do now?

Community
  • 1
  • 1
Amit Pal
  • 10,604
  • 26
  • 80
  • 160

1 Answers1

1

You should use custom search view in order to access to EditText in toolbar (app:actionViewClass property in menu layout). After set TextWathcer and manage spans inside afterTextChanged callback.

I wrote some example with basic background spans implementation. It is main concept and start point in solving your issue.

See example below:

menu_main.xml:

<item android:id="@+id/action_search"
    android:title="search"
    android:icon="@drawable/ic_search"
    app:showAsAction="ifRoom|collapseActionView"
    android:hint="Enter Tags"
    app:actionViewClass="your.package.CustomSearchView" />

CustomSearchView.java:

public class CustomSearchView extends SearchView {

    private AutoCompleteTextView mSearchAutoComplete;

    public CustomSearchView(Context context) {
        super(context);
        initialize();
    }

    public CustomSearchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    public CustomSearchView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize();
    }

    public void initialize() {
        mSearchAutoComplete = (AutoCompleteTextView) findViewById(android.support.v7.appcompat.R.id.search_src_text);

        if (mSearchAutoComplete == null) {
            Log.wtf("TEST", "Some Changes in AppCompat????");
            return;
        }
        mSearchAutoComplete.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mSearchAutoComplete.removeTextChangedListener(this);
                setSpans(s, Color.RED);
                mSearchAutoComplete.addTextChangedListener(this);
            }
        });
    }

    private void setSpans(Editable s, @ColorInt int backgroundColor) {
        BackgroundColorSpan[] spans = s.getSpans(0, s.length(), BackgroundColorSpan.class);

        String[] words;
        if (s.toString().endsWith(" ")) {
            words = (s.toString() + "X").split("\\s");
        } else {
            words = s.toString().split("\\s");
        }
        int completedWordsCount = words.length - 1;
        if (spans.length != completedWordsCount) {
            for (BackgroundColorSpan span : spans) {
                s.removeSpan(span);
            }

            int currentIndex = 0;
            for (int i = 0; i < words.length - 1; i++) {
                s.setSpan(new BackgroundColorSpan(backgroundColor), currentIndex, currentIndex + words[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                currentIndex += words[i].length() + 1;
            }
        }
    }
}

P.S. This link might be also useful for you in order to set Clickable spans - Link.

Oleksandr
  • 6,226
  • 1
  • 46
  • 54
  • Thanks for answering it. Will `mSearchAutoComplete = (AutoCompleteTextView) findViewById(android.support.v7.appcompat.R.id.search_src_text);` will be `mSearchAutoComplete = (AutoCompleteTextView) findViewById(android.support.v7.appcompat.R.id.search_src_text);` ? – Amit Pal Oct 23 '15 at 09:20
  • I am not showing any `AutoCompleteTextView`. User will add some string with spaces. After that I need to take these words and make a query – Amit Pal Oct 23 '15 at 09:24
  • @AmitPal Yes, you do not show, but this is how it is implemented inside Android source code. Look here - http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/widget/SearchView.java#116. – Oleksandr Oct 23 '15 at 09:27
  • @AmitPal If you want you can replace AutoCompleteTextView with EditText. Your control will work exactly the same as EditText until you set adapter to AutoCompleteTextView. – Oleksandr Oct 23 '15 at 09:29
  • Ah! I see. BTW I am getting these errors in above code : http://pastebin.com/z3JCUY3V Please have a look at it – Amit Pal Oct 23 '15 at 09:30
  • @AmitPal Sorry, I did a typo. mSearchAutoComplete should be `private AutoCompleteTextView mSearchAutoComplete`. See edited answer – Oleksandr Oct 23 '15 at 09:34
  • and `action_s` will be replaced by ? – Amit Pal Oct 23 '15 at 09:36
  • @AmitPal, I don't understand what action_s do you mean? – Oleksandr Oct 23 '15 at 09:38
  • I don't have `action_s` in my menu item. Are you referring to `action_search` (Please have a look at menu_main in your answer). If yes, then I am still getting the `could not find symbol variable action_search` where as the `Id` is same in `` . Why is to so? It's not even showing on auto suggestions – Amit Pal Oct 23 '15 at 09:42
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/93146/discussion-between-alexandr-and-amit-pal). – Oleksandr Oct 23 '15 at 09:45