0

I'm trying to build an application in which I have 5 tabs, and each tab loads its own particular fragment, I'm looking a way how to change the tab Icon when I switch between fragments.

I tried setting that by changing the Image inside the fragment class, but when I click the other tab it still stays, not changing back to "not active image icon"

Not using Action bar, not using ViewPager also, those 5 tabs are just ImageViews which are clickable, not the TabHost

Thanks for your help.

2 Answers2

0

I'm assuming you're using the ActionBar for the tabs, if not, see this example.

You can use ActionBar.Tab.setIcon() to set the icon for the tab.

f2prateek
  • 2,034
  • 2
  • 20
  • 26
0

It is very bad idea to set tab icon from fragment, you should set icons from Activity (for example onCreate method). You probably need to create selector for each tab icon( selected and default icon) Read about selector there: http://developer.android.com/guide/topics/resources/drawable-resource.html

You create 1 file for each tab. For example ic_tabs_first.xml. You have two icon, one ic_tabs_first_default.png, second ic_tabs_first_selected.png. Your ic_tabs_first.xml should be like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
          android:drawable="@drawable/ic_tabs_first_selected" /> <!-- pressed -->
     <item android:state_selected="true"
          android:drawable="@drawable/ic_tabs_first_selected" /> <!-- selected -->
     <item android:drawable="@drawable/ic_tabs_first_default" /> <!-- default -->
</selector>
  • I tried this, but the the icon is changing only in the pressed state, but it is not staying when its is selected –  Oct 02 '13 at 18:02
  • Very good example is here http://www.mkyong.com/android/android-tablayout-example/ possible this post question is duplicate for http://stackoverflow.com/questions/773690/android-customizing-tabs-on-state-how-do-i-make-a-selector-a-drawable. – user2630548 Oct 02 '13 at 18:09
  • those 5 tabs are just ImageViews which are clickable not the TabHost –  Oct 02 '13 at 18:23
  • The best way is to use tabhost, but if you want you can use toogleButton(it can be checked or not), not imageView – user2630548 Oct 02 '13 at 18:32
  • Very simple and clear example with tabsHost with fragments is here http://maxalley.wordpress.com/2013/05/18/android-creating-a-tab-layout-with-fragmenttabhost-and-fragments/ – user2630548 Oct 02 '13 at 18:37
  • I cannot use it, because I have the animation stuff, on keydown animation, which are simpler implementing in this way –  Oct 02 '13 at 20:25