1

我在活动启动时请求焦点的活动上有一个 EditText。这对于没有启用 TalkBack 的用户来说非常有用。但是,对于可访问性(即对于启用了 TalkBack 的用户),我需要将焦点设置在屏幕的标题栏上,而不是 EditText。

我尝试了几件事,但未能成功将焦点设置在标题栏的 textview 上(我检查了 titleTextView 不返回 null):

Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

TextView titleTextView = null;
//get the tool bar's title TextView
try
{
    Class<?> toolbarClass = Toolbar.class;
    Field titleTextViewField = toolbarClass.getDeclaredField("mTitleTextView");
    titleTextViewField.setAccessible(true);
    titleTextView = (TextView)titleTextViewField.get(toolbar);
}
catch (NoSuchFieldException | IllegalAccessException e)
{
    e.printStackTrace();
}

if (titleTextView != null)
{
    titleTextView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
    AccessibilityManager manager = (AccessibilityManager)getSystemService(Context.ACCESSIBILITY_SERVICE);
    if (manager.isEnabled())
    {
        AccessibilityEvent e = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_FOCUSED);
        e.setSource(titleTextView);
        e.setEventType(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
        e.setClassName(getClass().getName());
        e.setPackageName(getPackageName());
        e.getText().add("Message");
        manager.sendAccessibilityEvent(e);          
    }

当 TalkBack 开启时,titleTextView 永远不会获得焦点。

任何帮助,将不胜感激。

4

1 回答 1

3

我可以通过将代码移动到 if 块中来解决这个问题,如果用户启用了 TalkBack,则只执行块中的代码。也就是说,accessibilityManager.isEnabled() 只有在 TalkBack 开启时才会评估为 true:

AccessibilityManager am = (AccessibilityManager)getSystemService(Context.ACCESSIBILITY_SERVICE);
if (am.isEnabled())
{
    Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(actionBar);
    toolbar.setFocusable(true);
    toolbar.setFocusableInTouchMode(true);
    try
    {               
        Class<?> toolbarClass = Toolbar.class;
        Field titleTextViewField = toolbarClass.getDeclaredField("mTitleTextView");
        titleTextViewField.setAccessible(true);
        TextView titleTextView = (TextView)titleTextViewField.get(toolbar);
        titleTextView.setFocusable(true);
        titleTextView.setFocusableInTouchMode(true);
    }
    catch (NoSuchFieldException | IllegalAccessException e)
    {               
        e.printStackTrace();            
    }
    toolbar.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
    AccessibilityEvent e = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
    e.setSource(toolbar);
    e.setEventType(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
    e.setClassName(getClass().getName());
    e.setPackageName(getPackageName());
    am.sendAccessibilityEvent(e);
}
于 2016-07-19T04:19:19.237 回答