草庐IT

android - 奇怪的行为 : Class type of the object retuned by the getText() method of TextView changes after creating AccessibilityNodeInfo of TextView

coder 2023-12-12 原文

我有一个带有文本“Hello World!”的 TextView。在布局 xml 中定义

TextView textView = (TextView)findViewById(R.id.textView);

TextView 的getText() 方法返回类java.lang.String 的对象

//Returns object of String class
Toast.makeText(getApplicationContext(), textView.getText().getClass().getName(), Toast.LENGTH_LONG).show();

如果在创建 AccessibilityNodeInfo 后调用它,则返回 android.text.SpannableString 的对象

//Creating AccessibilityNodeInfo
AccessibilityNodeInfo info = textView.createAccessibilityNodeInfo();

//Returns object of SpannableString
Toast.makeText(getApplicationContext(), "After creating AccessibilityNodeInfo: " + textView.getText().getClass().getName(), Toast.LENGTH_LONG).show();

创建 AccessibilityNodeInfo 与 getText() 方法返回的对象有什么关系?

注意:这只发生在 Android 4.3 及以上

最佳答案

这是由于selectcutcopypaste等新特性添加到AccessibilityNodeInfo。它在 Android 4.3 中引入并记录在案 here .

Select text and copy/paste

The AccessibilityNodeInfo now provides APIs that allow an AccessibilityService to select, cut, copy, and paste text in a node.

To specify the selection of text to cut or copy, your accessibility service can use the new action, ACTION_SET_SELECTION, passing with it the selection start and end position with ACTION_ARGUMENT_SELECTION_START_INT and ACTION_ARGUMENT_SELECTION_END_INT. Alternatively you can select text by manipulating the cursor position using the existing action, ACTION_NEXT_AT_MOVEMENT_GRANULARITY (previously only for moving the cursor position), and adding the argument ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN.

You can then cut or copy with ACTION_CUT, ACTION_COPY, then later paste with ACTION_PASTE.

Note: These new APIs are also available for previous versions of Android through the Android Support Library, with the AccessibilityNodeInfoCompat class.

要实现select 功能,styleable/markup 对象需要附加到底层文本。因此,文本类型从 String 更改为 SpannableString

这里是View.java的代码其中介绍了这个功能。以下代码将类型更改为 SpannableString

@Override
public CharSequence getIterableTextForAccessibility() {
    if (!(mText instanceof Spannable)) {
        setText(mText, BufferType.SPANNABLE);
    }
    return mText;
}

关于android - 奇怪的行为 : Class type of the object retuned by the getText() method of TextView changes after creating AccessibilityNodeInfo of TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23610393/

有关android - 奇怪的行为 : Class type of the object retuned by the getText() method of TextView changes after creating AccessibilityNodeInfo of TextView的更多相关文章

随机推荐