Get the value of link text when clicked in a textview in android

后端 未结 3 779
你的背包
你的背包 2020-12-14 11:14

I have a TextView. I have added custom links like \"@abc\", \"#android\" by matching some regex pattern. The links are dis

3条回答
  •  天涯浪人
    2020-12-14 11:55

    Here is a pretty simple solution I found to get the value of the link inside the TextView when the user clicks on it. In this case I'm using phone numbers and it works like a charm.

    myTextView.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
                if(myTextView.getSelectionStart()== -1 && 
                        myTextView.getSelectionEnd() == -1){
                    Toast.makeText(getApplicationContext(), "You clicked outside the link", 
                            Toast.LENGTH_SHORT).show();
                }
                else {
    
                    int start = myTextView.getSelectionStart();
                    int end = myTextView.getSelectionEnd();
                    String selected = myTextView.getText().toString().substring(start, end);
    
                    Toast.makeText(getApplicationContext(), 
                            "Clicked: " + selected, 
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    

    Hope it helps.

提交回复
热议问题