在网上看了一个帖子如何自由选择TextView的文字的,感觉还不错。想分析一下源码,但是网速不好,等下载下了源码再看吧,在线的打不开。
我就把实现的代码贴出来吧,基本上就那个帖子上的代码:原理看完源码再补上
package com.example.view;
import android.content.Context;
import android.graphics.Color;
import android.text.Layout;
import android.text.Selection;
import android.text.method.MovementMethod;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MotionEvent;
import android.widget.EditText;
public class SelectedTextView extends EditText{
private int off;
public SelectedTextView(Context context) {
super(context);
init();
}
public SelectedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public SelectedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init(){
setGravity(Gravity.TOP);
this.setBackgroundColor(Color.WHITE);
}
@Override
protected boolean getDefaultEditable() {
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
Layout layout = getLayout();
int line = 0 ;
switch (action) {
case MotionEvent.ACTION_DOWN:
line = layout.getLineForVertical(getScrollY()+ (int )event.getY());
off = layout.getOffsetForHorizontal(line, (int )event.getX());
Selection.setSelection(getEditableText(), off);
break ;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
line = layout.getLineForVertical(getScrollY()+(int )event.getY());
int curOff = layout.getOffsetForHorizontal(line, ( int )event.getX());
Selection.setSelection(getEditableText(), off, curOff);
break ;
}
return true ;
}
}
布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />
<com.example.view.SelectedTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="abcdefghijklmnopqrstuvwxyzxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
/>
</RelativeLayout>