そこで、ClickableSpan.java をコピーして TouchableSpan.java を作成しました。
import android.text.TextPaint;
import android.text.style.CharacterStyle;
import android.text.style.UpdateAppearance;
import android.view.MotionEvent;
import android.view.View;
/**
* If an object of this type is attached to the text of a TextView
* with a movement method of LinkTouchMovementMethod, the affected spans of
* text can be selected. If touched, the {@link #onTouch} method will
* be called.
*/
public abstract class TouchableSpan extends CharacterStyle implements UpdateAppearance {
/**
* Performs the touch action associated with this span.
* @return
*/
public abstract boolean onTouch(View widget, MotionEvent m);
/**
* Could make the text underlined or change link color.
*/
@Override
public abstract void updateDrawState(TextPaint ds);
}
そして、私はに拡張LinkMovementMethod.java
しましたLinkTouchMovementMethod.java
。onTouchEvent メソッドは、onClick の記述が onTouch に変更され、新しい行が追加されていることを除いて、同じです。
import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.view.MotionEvent;
import android.widget.TextView;
public class LinkTouchMovementMethod extends LinkMovementMethod
{
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer,
MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP ||
action == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
TouchableSpan[] link = buffer.getSpans(off, off, TouchableSpan.class);
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
link[0].onTouch(widget,event); //////// CHANGED HERE
} else if (action == MotionEvent.ACTION_DOWN) {
link[0].onTouch(widget,event); //////// ADDED THIS
Selection.setSelection(buffer,
buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]));
}
return true;
} else {
Selection.removeSelection(buffer);
}
}
return super.onTouchEvent(widget, buffer, event);
}
}
コード内で MovementMethod を適切に設定します。
TextView tv = (TextView) findViewById(R.id.tv);
tv.setMovementMethod(new LinkTouchMovementMethod());
テキストを表示するには:
touchableSpan = new TouchableSpan() {
public boolean onTouch(View widget, MotionEvent m) {
...
}
public void updateDrawState(TextPaint ds) {
ds.setUnderlineText(false);
ds.setAntiAlias(true);
}
};
String rv = "Text to span";
text = new SpannableString(rv);
text.setSpan(touchableSpan, begin, end, 0);
tv.setText(text, BufferType.SPANNABLE);