Android TextView怎么双击复制一个英文单词?

Android TextView怎么双击复制一个英文单词?

TextView怎么双击复制一个英文单词,对于这个问题,查了很多文章,很少有实质性的解决方法,经过不懈努力,终于想了出来,特此分享。(效果图在文后
以下是TestTextView类

//TestTextView类
class TestTextView extends androidx.appcompat.widget.AppCompatTextView{
        private TestTextView self;//方便找自己
        private Context context;
        //用来分割单词的符号,可根据情况增减
        private final String[] spiltCharacter={",",":"," ",".","?","\"","\n"};
        protected long rootTime;//取开机时间

        /*构造*/
        @SuppressLint("ClickableViewAccessibility")
        public TestTextView(Context context) {
            super(context);
            this.context = context;
            rootTime = SystemClock.elapsedRealtime();//取已开机时间
            self = TestTextView.this;
            //设置触摸监听
            self.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == event.ACTION_DOWN){
                        //两次单击时间间隔在0.8秒内即达成双击事件
                        if (SystemClock.elapsedRealtime() - rootTime < 800) {
                            //根据按下位置取文本偏移量,偏移量最大值和文本长度一致
                            int offsetForPosition = self.getOffsetForPosition(event.getX(), event.getY());
                            System.out.println("文本偏移量 offsetForPosition:   "+offsetForPosition);
                            //若调用了append方法改变文本就会抛类型转换异常,所以此处需要用toString
                            String text =  self.getText().toString();
                            int textLength = text.length();//文本长度
                            int charIndex = 0;//点击的文本相对于text的索引
                            int wordStartIndex = -1;//单词开始索引位置
                            int wordEndIndex = 8192;//单词结束索引位置
                            if (offsetForPosition != 0){
                                charIndex = offsetForPosition-1;
                            }else {
                                charIndex = 0;
                            }

                            System.out.println("离点击位置最近的文本: "+text.charAt(charIndex));
                            //以索引为界分裂文本
                            String backwardText = text.substring(charIndex);//前一段文本
                            String forwardText = text.substring(0, charIndex);//后一段文本
                            //对spiltCharacter(分割单词的符号数组)遍历
                            for (String spiltCharacterItem : spiltCharacter) {
                                //判断索引位置是否为0
                                if (charIndex == 0){
                                    wordStartIndex = -1;//方便最后取文本
                                }else {
                                    //向文本前查找,取离索引位置最近的值作为单词开头
                                    if (forwardText.contains(spiltCharacterItem)){
                                        int spiltChaStartIndex = forwardText.lastIndexOf(spiltCharacterItem);
                                        wordStartIndex= Math.max(spiltChaStartIndex, wordStartIndex);
                                    }
                                }

                                // 判断索引位置是否为最大值
                                if (charIndex == textLength -1){
                                    wordEndIndex = backwardText.length()-1;//方便最后取文本(同上)

                                }else {
                                    //向文本后查找,取离索引位置最近的值作为单词结尾
                                    if (backwardText.contains(spiltCharacterItem)){
                                        int spiltChaEndIndex = backwardText.indexOf(spiltCharacterItem);
                                        wordEndIndex= Math.min(spiltChaEndIndex, wordEndIndex);
                                    }
                                }
                            }

                            System.out.println("(严格来说是符号的索引)wordStartIndex: "+wordStartIndex);
                            System.out.println("(单词末尾字母的索引)wordEndIndex:--------"+(wordEndIndex+charIndex));
                            //大功告成,取出文本
                            Toast.makeText(context,text.substring(wordStartIndex+1,wordEndIndex+charIndex),Toast.LENGTH_SHORT).show();
                        }
                        rootTime = SystemClock.elapsedRealtime();//更新时间
                    }
                    return true;
                }
            });
        }
    }

在MainActivity中使用(需要在布局中添加LinearLayout线性布局,id为 R.id.myLinear):

		LinearLayout viewById = findViewById(R.id.myLinear);
        TestTextView myTextView = new TestTextView(this);
        myTextView.setText("MyTextView"+"\n");
        myTextView.append("The GIADA Club spread over nearly 1,000 square meters, will be located in the hotel's west wing. The first floor will be home to a 353-square-meter GIADA boutique, while the 645-square-meter second floor will include a sky garden and an indoor dining space to create an Italian fine dining restaurant in partnership with renowned Italian chefs. The club's architecture is designed by Claudio Silvestrin, known for contemporary European minimalism. He previously designed GIADA's global flagship store on Via Montenapoleone in Milan."+"\n");
        myTextView.append("The GIADA Club will combine the elegance of Italian design with Beijing's historical and modern charms. The fusion of these two cultures is set to offer urban elites a unique social space, showcasing GIADA's brand ethos of luxury lifestyle,\" Zhao Yizheng, founder and president of Redstone Haute Couture, which acquired GIADA in 2011, said.");
        viewById.addView(myTextView);

总结以下:
思路流程:1.写双击事件
2.取离点击位置最近的文本的偏移量
3.将整个整个文本按照偏移量分为两段
4.前段向前寻找最近的分隔符的索引,后段也是
5.用找到的两个索引取出单词

核心方法:TestTextView.this.getOffsetForPosition(event.getX(), event.getY());根据点击位置取最近字母偏移量。假如一个短语BigApple,如果点击A的左半部分,此方法会取到g,点击A的右半部分会取到p,这是这个这个方法的小瑕疵
效果图:
Android TextView怎么双击复制一个英文单词?_第1张图片
如果帮到了你,点赞让更多的人看到!ღ( ´・ᴗ・` )比心

你可能感兴趣的:(学习交流)