How to use the OnTabChanged method in android?

Chetna picture Chetna · Jun 12, 2012 · Viewed 9.2k times · Source
       TabHost tabHost = getTabHost();  // The activity TabHost
    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
    Intent intent;  // Reusable Intent for each tab

    // Create an Intent to launch an Activity for the tab (to be reused)
    intent = new Intent().setClass(this, NewUserActivity.class);

    // Initialize a TabSpec for each tab and add it to the TabHost
    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth();

    spec = tabHost.newTabSpec("New User").setIndicator("New User").setContent(intent);
    tabHost.addTab(spec);

    // Do the same for the other tabs
    intent = new Intent().setClass(this, ExistingUserActivity.class);
    spec = tabHost.newTabSpec("Existing User").setIndicator("Existing User").setContent(intent);
    tabHost.addTab(spec);

    tabHost.getTabWidget()
            .getChildAt(0)
            .setLayoutParams(
                    new LinearLayout.LayoutParams((width / 2) - 2, 40));
    tabHost.getTabWidget()
            .getChildAt(1)
            .setLayoutParams(
                    new LinearLayout.LayoutParams((width / 2) - 2, 40));
    TabWidget tw = getTabWidget();

    tw.getChildAt(0).setBackgroundColor(Color.parseColor("#800000"));
    tw.getChildAt(1).setBackgroundColor(Color.parseColor("#FF6347"));

}

@Override
public void onTabChanged(String x) {

}

The above code initializes the TabHost . It uses two tabs. One- New User and another-Existing User. On clicking any of them, i want the tab to be focussed and of a different color than the other one. I have no idea how to use the OnTabChanged method.

Answer

Vipul picture Vipul · Jun 12, 2012

On clicking any of them, i want the tab to be focussed and of a different color than the other one.

You can implement it as follows.

tabHost.setOnTabChangedListener(new OnTabChangeListener() {

            public void onTabChanged(String str) {
                tabHost.getCurrentTabView().setBackgroundColor(color);
                tabHost.getCurrentTabView().setBackgroundDrawable(drawable);
                tabHost.getCurrentTabView().setBackgroundResource(resid);
            }
        });