I read a post on the Internet to learn how to freely select TextView text. I want to analyze the source code, but the network speed is not good. I can't open it online after I download the source code.
I will post the implementation code, basically the code on that post: after reading the source code, I will add it.
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);}@Overrideprotected boolean getDefaultEditable() {return false;} @Overridepublic 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 ; } }
Layout File
<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>