Skip to content

Instantly share code, notes, and snippets.

@fabricethilaw
Forked from dafi/ClickableTextView.java
Created January 13, 2017 11:28
Show Gist options
  • Save fabricethilaw/dc1bcc4c31e0ff1fa57fac313e1abb8e to your computer and use it in GitHub Desktop.
Save fabricethilaw/dc1bcc4c31e0ff1fa57fac313e1abb8e 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" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment