Android- How can I show text selection on textview?

前端 未结 2 1471
猫巷女王i
猫巷女王i 2020-12-01 07:15

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 m

2条回答
  •  难免孤独
    2020-12-01 07:34

    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);
            }
        }
    }
    

提交回复
热议问题