IAmKale
IAmKale

Reputation: 3426

How can I remove formatting from text that is pasted into a SearchView?

I discovered that pasting a selection of SpannableString into a SearchView preserves the string's spans. What's the best way to strip away all of that formatting when the string is pasted into the SearchView?

Here's an example of what's happening:

pasted spanned string into searchview

The text above was colored grey, italicized, and superscript'd prior to being pasted.

Upvotes: 3

Views: 1904

Answers (1)

Nikola Despotoski
Nikola Despotoski

Reputation: 50558

I'm not sure if there is way to detect if the text is pasted or hand-input directly in the SearchView query listeners, but you can bypass it like:

  1. Obtain the TextView from the search_plate layout of the SearchView
  2. Keep that reference (as public, perhaps)
  3. Add the OnQueryTextListener
  4. Remove any span from the string
  5. Use the TextView reference to re-set the text that has no span.

Please try it and let me know.

 int searchTextViewId = mSearchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
            mSearchTextView = (TextView) mSearchView.findViewById(searchTextViewId);
        mSearchView.setOnQueryTextListener(new OnQueryTextListener(){

            @Override
            public boolean onQueryTextChange(String arg0) {
                if(!TextUtils.isEmpty(arg0)){
                    arg0 = removeSpan(new SpannableString(arg0));
                    mSearchView.setOnQueryTextListener(null);
                    mSearchTextView.setText(arg0);
                    mSearchView.setOnQueryTextListener(this);
                }
                return false;
            }

            @Override
            public boolean onQueryTextSubmit(String query) {
                // TODO Auto-generated method stub
                return false;
            }});
        }


    private String removeSpan(Spannable s){
          s.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL),    0, s.length(),    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
          return s.toString();
    }

Also here is how to obtain last copied text from the Clipboard:

private boolean isTextPasted(Context context, String text){
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); 
        if(!clipboard.hasPrimaryClip()) 
            return false;

        ClipData clipData = clipboard.getPrimaryClip();
        String lastClipText = clipData.getItemAt(clipData.getItemCount()-1).coerceToText(context).toString();
        return !TextUtils.isEmpty(lastClipText) && lastClipText.equals(text);
    }

Which you might add to the condition in OnQueryTextListener.

Upvotes: 2

Related Questions