Swipe with tab host

nrofis picture nrofis · Apr 4, 2013 · Viewed 19.9k times · Source

I have a TabHost control (not in actionbar), and I want to make the tabs to change when the user swipes the context on each tab (something like whatsapp emoji tabs).
How can I do this?

EDIT
The feel is also important. I want that the contexts should have scroll animations (No matter if the user swipe or if the tab is clicked).

Answer

Toan Nguyen picture Toan Nguyen · Dec 2, 2013

You can override onTouchEvent:

@Override
public boolean onTouchEvent(MotionEvent touchevent) {
    switch (touchevent.getAction()) {
    // when user first touches the screen to swap
    case MotionEvent.ACTION_DOWN: {
        lastX = touchevent.getX();
        break;
    }
    case MotionEvent.ACTION_UP: {
        float currentX = touchevent.getX();

        // if left to right swipe on screen
        if (lastX < currentX) {

            switchTabs(false);
        }

        // if right to left swipe on screen
        if (lastX > currentX) {
            switchTabs(true);
        }

        break;
    }
    }
    return false;
}

switchTabs method:

public void switchTabs(boolean direction) {
        if (direction) // true = move left
        {
            if (tabHost.getCurrentTab() == 0)
                tabHost.setCurrentTab(tabHost.getTabWidget().getTabCount() - 1);
            else
                tabHost.setCurrentTab(tabHost.getCurrentTab() - 1);
        } else
        // move right
        {
            if (tabHost.getCurrentTab() != (tabHost.getTabWidget()
                    .getTabCount() - 1))
                tabHost.setCurrentTab(tabHost.getCurrentTab() + 1);
            else
                tabHost.setCurrentTab(0);
        }
    }