Android clipboard.getText() is deprecated; how then to get the text item that's in it?

拥有回忆 提交于 2020-06-14 07:43:51

问题


This works fine, showing me exactly what was the last string put into Android clipboard, which happens to be euswcnmst.

Log.w("clip", clipboard.getText().toString());

But getText is deprecated for clipboard objects.

Meanwhile, if I do Log.w("clip", clipboard.getPrimaryClip().toString());, I get this, exactly as shown ClipData { text/plain "label" {T:euswcnmst} }

I see what I want, and, assuming this format is always used for string clipboard items, I can use String functions (find : and subsequent } and do substring) to extract euswcnmst, but that's a hack.

What SHOULD I do?

EDIT

Based on Commonsware's Answer, here's what I should do:

ClipData clip = clipboard.getPrimaryClip();

if(clip == null || clip.getItemCount() == 0)
  return; // ... whatever; just don't go to next line

String t = clip.getItemAt(0).getText().toString();

EDIT 2

If the last ITEM in the clipboard was NOT text, the above code gives this error:

java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference

Here's the fix (I added the third line below):

if(   clip == null 
   || clip.getItemCount() == 0 
   || clip.getItemCount() > 0 && clip.getItemAt(0).getText() == null
  )
    return; // ... whatever; just don't go to next line

回答1:


Please understand that the clipboard is not purely for text. Complex constructs can be placed on the clipboard, in the form of 1 to N ClipData.Item objects inside the ClipData object that you are getting from getPrimaryClip().

Given your ClipData, call getItemCount() to determine the number of items. For whichever item(s) you wish to attempt to use, call getItemAt() on the ClipData to get the corresponding ClipData.Item. On that item, you can call getText() or coerceToText() to try to get a text representation of that item.




回答2:


Use below code

String copyString = clipboard.getPrimaryClip().getItemAt(0).getText()


来源:https://stackoverflow.com/questions/37196571/android-clipboard-gettext-is-deprecated-how-then-to-get-the-text-item-thats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!