无法将标题文本视图设置为辅助功能

时间:2016-07-18 23:41:13

标签: android accessibility android-accessibility

我在活动启动时请求焦点的活动上有一个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永远不会获得焦点。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

我能够通过将代码移动到if块中来解决这个问题,如果用户启用了TalkBack,则只执行块中的代码。也就是说,如果启用了TalkBack,accessibilityManager.isEnabled()将仅评估为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);
}

答案 1 :(得分:0)

在我看来,这行得通(kotlin):

view.post {
 this.isFocusable = true
 this.isFocusableInTouchMode = true
 this.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED)
}