Android Button vs TextView - Hyperlink like behavior

android, java

Solution

hotveryspicy gave a great answer and really pointed me in the right direction. Thank you, but I had a few issues with the response.

What I want is a button that has Black text and a Gray background in its normal state and a Red background with White text in its selected state. Like this:

Using hotveryspicy's suggestions I had the following issues:

I get an error when trying to assign a drawable to textColor. Funny but I see other references to doing this sort of thing. Maybe the XML validation is stricter now?

I also got an error if I didn't define a android:drawable in the buttonselector.xml. It seems you can set the color of a drawable in a selector eiter, you need to actually create a drawable.

Anyhow this is what I did:

I created a Color State Resource that looks like this:

File: res/colors/link_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#ffffff"/> 
    <item android:color="#000000"/> 
</selector>

Then the following 3 drawables:

My button background in its normal state using a Shape Drawable: File: res/drawable/link_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">
    <solid  android:color="#cccccc"/>
</shape>

My button background in its selected state, also a Shape Drawable: File: res/drawable/link_button_selected.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">
    <solid  android:color="#ff0000"/>
</shape>

Then I created a Drawable Selector that chooses between the 2 shapes. File: res/drawable/link_button_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

 <item 
     android:drawable="@drawable/link_button_selected"
     android:state_pressed="true" />

 <item 
     android:drawable="@drawable/link_button" />
</selector>

Then in my layout my button looks like this:

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="Button"
    android:textColor="@color/link_button" 
    android:background="@drawable/link_button_selector"
    />

Thanks for the help everyone!

Problem

On an Android View, I want to have a some clickable text that works similar to a webpage hyperlink. It looks just like normal text (no button border), but when touched, I want the text color to change and I may also want its background to turn a reverse color. Is it better to use a Button with a transparent background or a TextView. When should I choose one over the other? Thanks much

Original source