Search code examples
androidandroid-tabhost

Workaround for the absence TabSpec.setIndicator(View view) on Android API level <4


I need to use my custom view for the indicators of my TabHost. With Android API level >=4 no problem but in the Android API level <4 this method is not implemented. Any suggestion?

I was thinking to implement this method but unfortunately the TabHost class does not allow changes because has all attributes private and not protected.

Thanks.


Solution

  • I suggest use reflection:

    private void setIndecator(TabHost.TabSpec tabSpec, String label) {
        LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout tabView = (LinearLayout) vi.inflate(R.layout.tab_view, null);
        ((TextView)tabView.findViewById(R.id.tabCaption)).setText(label);
        try {
            Method m = tabSpec.getClass().getMethod("setIndicator", View.class);
            m.invoke(tabSpec, tabView);
        } catch (Exception e) {
            //in case if platform 1.5 or via other problems indicator cannot be set as view
            //we have to set as just simple label.
            tabSpec.setIndicator(label, getResources().getDrawable(R.layout.tab_selector));
        }
    }