Android - Programmatic scrolling of TabWidget

假装没事ソ 提交于 2019-12-04 16:58:57

You must both focusCurrentTab(int i) and setCurrentTab(int i). focusCurrentTab(i) will focus the UI of the TabWidget to the ith tab (what you want), and, as you already know, setCurrentTab(i) will focus the actual content of the ith tab in the main View.

For reference: http://developer.android.com/reference/android/widget/TabWidget.html#focusCurrentTab(int)

EDIT:

My answer was incorrect. This is the correct one (that the the poster found out themself):

It turns out that the TabWidget views had focusableInTouchMode set to false. As per View.java documentation:

A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false), or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode}) while the device is in touch mode. To correct the problem I iterated over the TabWidget views and set them focusable in touch mode:

for (int i = 0; i < count; i++) {
    getTabWidget().getChildAt(i).setFocusableInTouchMode(true);
}

set to TabHost next OnTabChangeListener:

@Override
public void onTabChanged(final String tag) {
    View tabView = tabHost.getCurrentTabView();
    int scrollPos = tabView.getLeft() - (tabsHorizontalScrollView.getWidth() - tabView.getWidth()) / 2;
    tabsHorizontalScrollView.smoothScrollTo(scrollPos, 0);
}

It turns out that the TabWidget views had focusableInTouchMode set to false. As per View.java documentation:

A view will not actually take focus if it is not focusable ({@link #isFocusable} 
returns false), or if it is focusable and it is not focusable in touch mode 
({@link #isFocusableInTouchMode}) while the device is in touch mode.

To correct the problem I iterated over the TabWidget views and set them focusable in touch mode:

for (int i = 0; i < count; i++) {
    getTabWidget().getChildAt(i).setFocusableInTouchMode(true);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!