如何从textview android获取超链接文本?

时间:2016-02-10 09:39:01

标签: android hyperlink textview

我正在text-view.in上工作,文本视图显示html超链接。 当我点击超链接文本然后我想得到那个文本。

如上图所示,如果我点击超链接,那么我想显示文字。

您的回答将不胜感激

2 个答案:

答案 0 :(得分:1)

LinkEnableTextView类是这样的:

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ClickableSpan;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;


public class LinkEnabledTextView  extends TextView
{
// The String Containing the Text that we have to gather links from private SpannableString linkableText;
// Populating and gathering all the links that are present in the Text
private ArrayList<Hyperlink> listOfLinks; 

// A Listener Class for generally sending the Clicks to the one which requires it
TextLinkClickListener mListener;

// Pattern for gathering @usernames from the Text
Pattern screenNamePattern = Pattern.compile('(@[a-zA-Z0-9_]+)');

// Pattern for gathering #hasttags from the Text
Pattern hashTagsPattern = Pattern.compile('(#[a-zA-Z0-9_-]+)');

// Pattern for gathering http:// links from the Text
Pattern hyperLinksPattern = Pattern.compile('([Hh][tT][tT][pP][sS]?:\\/\\/[^ ,'\'>\\]\\)]*[^\\. ,'\'>\\]\\)])');

public LinkEnabledTextView(Context context, AttributeSet attrs)
{
    super(context, attrs);
    listOfLinks = new ArrayList<Hyperlink>();

}

public void gatherLinksForText(String text)
{
    linkableText = new SpannableString(text);
 //gatherLinks basically collects the Links depending upon the Pattern that we supply
 //and add the links to the ArrayList of the links

    gatherLinks(listOfLinks, linkableText, screenNamePattern);
    gatherLinks(listOfLinks, linkableText, hashTagsPattern);
    gatherLinks(listOfLinks, linkableText, hyperLinksPattern);

    for(int i = 0; i< listOfLinks.size(); i++)
    {
        Hyperlink linkSpec = listOfLinks.get(i);
        android.util.Log.v('listOfLinks :: ' + linkSpec.textSpan, 'listOfLinks :: ' + linkSpec.textSpan);

        // this process here makes the Clickable Links from the text

        linkableText.setSpan(linkSpec.span, linkSpec.start, linkSpec.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }


     // sets the text for the TextView with enabled links

    setText(linkableText);
}


 // sets the Listener for later click propagation purpose

public void setOnTextLinkClickListener(TextLinkClickListener newListener)
{
    mListener = newListener;
}

  //The Method mainly performs the Regex Comparison for the Pattern and adds them to
  //listOfLinks array list


private final void gatherLinks(ArrayList<Hyperlink> links,
                               Spannable s, Pattern pattern)
{
    // Matcher matching the pattern
    Matcher m = pattern.matcher(s);

    while (m.find())
    {
        int start = m.start();
        int end = m.end();


    // Hyperlink is basically used like a structure for storing the information about
    // where the link was found.

        Hyperlink spec = new Hyperlink();

        spec.textSpan = s.subSequence(start, end);
        spec.span = new InternalURLSpan(spec.textSpan.toString());
        spec.start = start;
        spec.end = end;

        links.add(spec);
    }
}


// This is class which gives us the clicks on the links which we then can use.


public class InternalURLSpan extends ClickableSpan
{
    private String clickedSpan;

    public InternalURLSpan (String clickedString)
    {
        clickedSpan = clickedString;
    }

    @Override
    public void onClick(View textView)
    {
        mListener.onTextLinkClick(textView, clickedSpan);
    }
}


// Class for storing the information about the Link Location


class Hyperlink
{
    CharSequence textSpan;
    InternalURLSpan span;
    int start;
    int end;
}

现在,有了这个,你只需要另一个界面来将点击传播到你需要处理它们的地方我在我的Activity中实现了界面,简单地在那里写了一个Log Command。 TextLinkClickListener接口如下所示:

import android.view.View;

public interface TextLinkClickListener
{


  //  This method is called when the TextLink is clicked from LinkEnabledTextView

public void onTextLinkClick(View textView, String clickedString)
}

完成所有这些后,您只需要使用Custom LinkEnabledTextView创建一个Activity并自行检查。在创建自定义LinkEnabledTextView的对象时,您必须执行一些操作,这些对象在下面的活动代码中提到并描述:

import android.text.method.MovementMethod;
import com.umundoinc.Tvider.Component.LinkEnabledTextView.LinkEnabledTextView;
import com.umundoinc.Tvider.Component.LinkEnabledTextView.TextLinkClickListener;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.View;

//Here the Activity is implementing the TextLinkClickListener the one we have created
//the Clicks over the Links are forwarded over here from the LinkEnabledTextView

public class TextViewActivity  extends Activity  implements TextLinkClickListener 
{
private LinkEnabledTextView check;
protected void onCreate(Bundle savedInstance)
{
    super.onCreate(savedInstance);

    String text  =  "This is a #test of regular expressions with http://example.com/ links as used in @twitter for performing various operations based on the links this handles multiple links like http://this_is_fun.com/ and #Awesomess and @Cool";

    check = new LinkEnabledTextView(this, null);
    check.setOnTextLinkClickListener(this);
    check.gatherLinksForText(text);
    check.setTextColor(Color.WHITE);
    check.setLinkTextColor(Color.GREEN);

    MovementMethod m = check.getMovementMethod();
    if ((m == null) || !(m instanceof LinkMovementMethod)) {
        if (check.getLinksClickable()) {
            check.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }

    setContentView(check);
}

public void onTextLinkClick(View textView, String clickedString)
{
    android.util.Log.v('Hyperlink clicked is :: ' + clickedString, 'Hyperlink clicked is :: ' + clickedString);
}

希望它会对你有所帮助!!

答案 1 :(得分:1)

请尝试我的实施:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ........

     textView mTvTxt = findViewById(R.id.tv_txt_view);

    final String hyperlink =  "Vasant jetava";  

    SpannableString spannableString = makeLinkSpan(hyperlink , new View.OnClickListener() {
        @Override
        public void onClick(View v) {
               showDialog(hyperlink)
        }
    });

    mTvTxt.setText(getString("hello whats up man....");
    mTvTxt.append(spannableString);
    makeLinksFocusable(mTvTxt);
}       
 private SpannableString makeLinkSpan(CharSequence text, View.OnClickListener listener) {

    SpannableString link = new SpannableString(text);
    link.setSpan(new ClickableString(listener), 0, text.length(),
            SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
    return link;


private void makeLinksFocusable(TextView tv) {
    MovementMethod m = tv.getMovementMethod();
    if ((m == null) || !(m instanceof LinkMovementMethod)) {
        if (tv.getLinksClickable()) {
            tv.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }
}



private static class ClickableString extends ClickableSpan {
        private View.OnClickListener mListener;

        public ClickableString(View.OnClickListener listener) {
            mListener = listener;
        }

        @Override
        public void onClick(View v) {
            mListener.onClick(v);
        }
    }
private void showDialog(String message){
        AlertDialog alertDialog = new AlertDialog.Builder(<YourActivityName>this).create(); //Read Update
        alertDialog.setTitle("Alert Dialog");
        alertDialog.setMessage(message);

        alertDialog.setButton("Continue..", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // here you can add functions
            }
        });

        alertDialog.show();
    }