Skip to content

Instantly share code, notes, and snippets.

@dafi
Created November 26, 2013 12:49
Show Gist options
  • Save dafi/7657781 to your computer and use it in GitHub Desktop.
Save dafi/7657781 to your computer and use it in GitHub Desktop.
Android TextView changing color when clicked. It uses the setSelect(); to change color. Show how to change text color and background
package com.ternaryop.phototumblrshare.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
public class ClickableTextView extends TextView implements OnTouchListener {
public ClickableTextView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
setup();
}
public ClickableTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
public ClickableTextView(Context context, int checkableId) {
super(context);
setup();
}
public ClickableTextView(Context context) {
super(context);
setup();
}
private void setup() {
setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (hasOnClickListeners()) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
setSelected(true);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
setSelected(false);
break;
}
}
// allow target view to handle click
return false;
}
}
<com.ternaryop.phototumblrshare.widget.ClickableTextView
android:id="@+id/title_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/thumbnail"
android:layout_toRightOf="@+id/thumbnail"
android:textColor="@drawable/text_link_selector"
android:background="@drawable/text_link_selector_bg"
android:textSize="15sp"
android:textStyle="bold"
android:typeface="sans" />
@souravsoftwareer
Copy link

hfh

Copy link

ghost commented Feb 9, 2017

👍

@SirCosty
Copy link

SirCosty commented Jan 19, 2018

Have try it but the function hasOnClickListeners() return always false and doesn't execute the inside code.
Do you know where might be the issue?
I had to extend the android.support.v7.widget.AppCompatTextView instead android.widget.TextView might be there the problem?

@lahirudnanajaya785
Copy link

Thanks Bro👍

@srijanC2306
Copy link

what is depedency

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment