Search code examples
androidandroid-tabhosttextview

Image is stretched in textview on runtime in tabhost


<TabHost
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="0dip"
            android:layout_marginRight="0dip" >

            <TextView
                android:id="@+id/view_all"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:tag="tab0"
                android:text="View All" />

            <TextView
                android:id="@+id/favourite"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:tag="tab1"
                android:text="Favourite" />

            <TextView
                android:id="@+id/make_fav"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:tag="tab2"
                android:background="@drawable/prev_button" />
        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

        </FrameLayout>
    </LinearLayout>
</TabHost>

Trying to change textview(make_fav) image at runtime by using below code on onTabChanged() of TabHost. Basically I want to change the image when user clicks on tab.

LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tabHost.getCurrentTabView().setBackgroundResource(R.drawable.prev_button);
tabHost.getCurrentTabView().setLayoutParams(params);

Question: How can I get the 9-patch image to not stretch, even though it displays properly in xml?


Solution

  • create xml like below

    tab_image.xml

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true" 
            android:drawable="@drawable/tab_pressed_image" />
        <item android:state_focused="true"
            android:drawable="@drawable/tab_pressed_image" />
        <item
            android:drawable="@drawable/simple_image" />
    </selector>
    

    put this xml under drawable directory and just set this image as background of tab.