Skip to content

Instantly share code, notes, and snippets.

@lidemin
Created May 15, 2014 08:24
Show Gist options
  • Save lidemin/6a16a69bd44a8fe5da6b to your computer and use it in GitHub Desktop.
Save lidemin/6a16a69bd44a8fe5da6b to your computer and use it in GitHub Desktop.
SelectableTextView
package com.damon.view;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.GestureDetectorCompat;
import android.text.Spanned;
import android.text.style.BackgroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
/**
* Created by damon on 15/5/14.
*/
public class SelectableTextView extends EditText {
private static final String TAG = "SelectableTextView";
public SelectableTextView(Context context) {
super(context);
init();
}
public SelectableTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SelectableTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private GestureDetectorCompat detector;
private void init(){
detector = new GestureDetectorCompat(getContext(),new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onDoubleTap(MotionEvent e) {
onDoubleClick(e);
return true;
}
});
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return detector.onTouchEvent(event);
}
});
}
private void onDoubleClick(MotionEvent e){
Log.d(TAG, "onDoubleClick:" + e.toString());
int line = getLayout().getLineForVertical(getScrollY()+(int)(e.getY() - getTextSize()/2));
int currentOffset = getLayout().getOffsetForHorizontal(line, (int) (e.getX()- getTextSize()/2));
Log.d(TAG, "click offset:" + currentOffset);
char[] tempCharArray = getText().toString().toCharArray();
while(!isWordCharacter(tempCharArray[currentOffset])){
currentOffset++;
}
int endCursor = currentOffset;
while(endCursor<tempCharArray.length){
if(!isWordCharacter(tempCharArray[endCursor])){
break;
}
endCursor++;
}
int startCursor = currentOffset;
while(startCursor<tempCharArray.length){
if(!isWordCharacter(tempCharArray[startCursor])){
break;
}
startCursor--;
}
startCursor++;
Log.d(TAG, "click word:[" + getText().toString().substring(startCursor, endCursor)+"]");
getText().setSpan(new BackgroundColorSpan(Color.GREEN), startCursor, endCursor, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
private boolean isWordCharacter(char c){
return (c>='a' && c<='z')
|| (c>='A' && c<='Z')
|| c=='-'
|| c=='\'';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment