Android- How can I show text selection on textview?

Rohit picture Rohit · Sep 10, 2012 · Viewed 17.6k times · Source

I am implementing a epub reading app where I am using textview for showing text of epub. I want to select text from textview when user long presses on textview and then do multiple operations on selected text of textview like highlight etc.. So, How can I show those cursors to user to select text whatever user wants.

*I dont want to use EditText and make it look like textview. May be overriding textview is prefered.

*I have attached screenshot to explain what I am looking for-

Screenshot from moon+reader to show text selection in it which I want in my app

Answer

Ray Zhou picture Ray Zhou · Jun 16, 2013

This is asked long time ago, when I had this problem myself as well. I made a Selectable TextView myself for my own app Jade Reader. I've hosted the solution to GitHub. (The code at BitBucket ties to the application, but it's more complete and polished.)

Selectable TextView (on GitHub)

Jade Reader (on BitBucket)

selection

Using the following code will make your TextView selectable.

package com.zyz.mobile.example;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class MainActivity extends Activity {

    private SelectableTextView mTextView;
    private int mTouchX;
    private int mTouchY;
    private final static int DEFAULT_SELECTION_LEN = 5;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // make sure the TextView's BufferType is Spannable, see the main.xml
        mTextView = (SelectableTextView) findViewById(R.id.main_text);
        mTextView.setDefaultSelectionColor(0x40FF00FF);


        mTextView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showSelectionCursors(mTouchX, mTouchY);
                return true;
            }
        });
        mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTextView.hideCursor();
            }
        });
        mTextView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mTouchX = (int) event.getX();
                mTouchY = (int) event.getY();
                return false;
            }
        });
    }

    private void showSelectionCursors(int x, int y) {
        int start = mTextView.getPreciseOffset(x, y);

        if (start > -1) {
            int end = start + DEFAULT_SELECTION_LEN;
            if (end >= mTextView.getText().length()) {
                end = mTextView.getText().length() - 1;
            }
            mTextView.showSelectionControls(start, end);
        }
    }
}