Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make TextView turn orange when focused?

Tags:

android

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

like image 320
user246114 Avatar asked Aug 03 '26 07:08

user246114


1 Answers

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">
    <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.

like image 162
Octavian A. Damiean Avatar answered Aug 05 '26 23:08

Octavian A. Damiean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!