在textview中创建一个超链接

时间:2015-04-07 09:46:12

标签: android textview

我正在创建一个聊天应用程序,每当我输入一些文本并按发送时,我会以编程方式创建一个新的TextView并添加到我现有的LinearLayout这样的内容 -

public void addTextView(LinearLayout view, String text) {
        TextView chatTextView = new TextView(getActivity());
        chatTextView.setLinksClickable(true);
        chatTextView.setMovementMethod(LinkMovementMethod.getInstance());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        chatTextView.setLayoutParams(lp);
       // chatTextView.setAutoLinkMask(Linkify.ALL);
        chatTextView.setText("me: " + Html.fromHtml(text));
        view.addView(chatTextView);    
    }

根据answer 1this question我向chatTextView.setMovementMethod(LinkMovementMethod.getInstance());添加了TextView,但我的链接仍无法点击。 (在模拟器上测试,此代码在片段中)

我想在这里添加的文字是 -

<a href="http://www.google.com">url</a>

尝试过 -

  1. autoLink = web(它会突出显示直接网址(即www.google.com),但不会突出显示超链接(即href)。
  2. Linkify.WEB_URL
  3. 修改

    我现在测试并发现如果textview来自xml布局,setMovementMethod可以正常使用超链接,但如果它是动态的,它就不起作用。

3 个答案:

答案 0 :(得分:1)

使用此

TextView textView =(TextView)findViewById(R.id.textView);
textView.setClickable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='http://www.google.com'> Google </a>";
textView.setText(Html.fromHtml(text));

答案 1 :(得分:0)

    mTextView.setClickable(true);
    final String text  = Html.fromHtml(getActivity().getResources().getString(R.string.url)).toString();
    mTextView.setMovementMethod(LinkMovementMethod.getInstance());
    mTextView.setText(text);

string.xml

<string name="url"><a href='http://www.google.com'> Google </a></string>

这对我来说非常适合,试试吧

答案 2 :(得分:0)

你可以用这个:

String text = "<font color=#ff0000><b><u>"+ "click here" +"</b></u></font>";
textview.setText(Html.fromHtml(text));
textview.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

Intent internetIntent = new Intent(Intent.ACTION_VIEW,
                                        Uri.parse("http://www.google.com"));
internetIntent.setComponent(new ComponentName("com.android.browser","com.android.browser.BrowserActivity"));
                                        internetIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        context.startActivity(internetIntent);
                                    }
                                });