tags:

views:

55

answers:

2

Hi,

I have a textview, I set it as clickable and focusable - how do I get it to highlight to orange (like a button) when the user focuses it with the trackwheel etc?:

TextView tv = ...;
tv.setClickable(true);
tv.setFocusable(true);

Thanks

A: 

I have no chance to try it at the moment, but what about adding a OnFocusChangeListener to your TextView and then use the setBackgroundColor(int color) method to change the background to orange

Martin
+3  A: 

This is quite easy. Here is the solution.

You have an TextView element with its background attribute set to @drawable/tbselector like this.

<TextView android:text="My text" 
    android:id="@+id/tv01"
    android:layout_width="300dip"
    android:layout_height="150dip"
    android:layout_gravity="center_horizontal"  
    android:background="@drawable/tbselector"/>

The last attribute android:background is essential the other stuff is up to you.

Now you create a tbselector.xml in your drawable subdirectory. Which looks like this.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    <item
        android:drawable="@drawable/bgdefault"
        android:state_focused="false"
        android:state_selected="false"/>
    <item
        android:drawable="@drawable/bgselected"
        android:state_focused="true"
        android:state_selected="false"/>
</selector>

Now you create a bgdefault.xml in your drawable subdirectory which looks like this.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="200dip"
        android:height="150dip"
        android:color="#00FF00"/>
    <solid
        android:color="#00FF00"/>
</shape>

Finally create a bgselected.xml in your drawable subdirectory which looks like the other one with other color values like this for example.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="200dip"
        android:height="150dip"
        android:color="#FFFF00"/>
    <solid
        android:color="#FFFF00"/>
</shape>

And thats it you now have a state dependent TextView background. You can however decide to set your drawables in your selector XML it's totally up to you. My values are just random values to show you the difference.

Hope it helps.

Octavian Damiean
I am going to deflate 200 textviews while loading. seems to much of processing. is it fine? or i should do it at touch/Focus listener?
Ankit Jain
I can't really tell to be honest. I guess it's not going to be more to process than doing it the programmatic way. If you'd like to try it (given that you have the time to) and get back to me with the results it#d be great.
Octavian Damiean