0

我正在为 android 编写一个应用程序,我试图将字符串的一部分超链接到应用程序中的另一个页面,但我正在为如何做到这一点而苦苦挣扎。

我设法让它与这样的整个文本视图一起工作:

TextView txtVirus = (TextView) findViewById(R.glossaryMalwareID.txtVirus);      
txtVirus.setText(Html.fromHtml("<U>Computer Virus<U>"));        
txtVirus.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            startActivity(new Intent ("com.digitalsecurity.app.GLOSSARYVIRUS"));
        }
    });     

然而,这意味着字符串必须在一个完全新的行上(或者我相信)。

我想要的是能够按照以下代码中的注释显示:

        TextView txtVirus = (TextView) findViewById(R.glossaryMalwareID.virusmain);     
    txtVirus.setText(Html.fromHtml("<br>" +
            "A Computer Virus is a small peice of " +
            "Software" +//i want the word 'software' hyperlinked to another page in my program
            "so on and so on"));
4

2 回答 2

1

经过 4 小时的搜索和调整,我得到了答案:

TextView txtVirus = (TextView) findViewById(R.glossaryMalwareID.virusmain);

    // this is the text we'll be operating on
    SpannableString text = new SpannableString("A Computer Virus is a small peice of Software. to make this easier to");

    //stops it from flickering to another colour when string is pressed.
    text.setSpan(new ForegroundColorSpan(Color.WHITE), 0, 69, 0);

    // make "Software" (characters 37 to 45) 
    //runs when clickableSpan is pressed
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent ("com.digitalsecurity.app.MALWAREHOWTOPROTECT"));
        }
    };
    //this is what calls the method
    text.setSpan(clickableSpan, 37, 45, 0);
    //underlines it
    text.setSpan(new URLSpan(""), 37, 45, 0);
    //turns it blue
    text.setSpan(new ForegroundColorSpan(Color.BLUE), 37, 45, 0);


    txtVirus.setMovementMethod(LinkMovementMethod.getInstance());

    // shove our styled text into the TextView
    txtVirus.setText(text, BufferType.SPANNABLE);

我从这里得到了帮助,它还有其他相当有用的格式化选项:

http://www.chrisumbel.com/article/android_textview_rich_text_spannablestring

我希望它可以帮助其他需要相同的人

于 2012-04-09T19:41:52.693 回答
0

如果显示链接,则对于您的 TextView,您Textview的外观如下:

TextView txtVirus = (TextView) findViewById(R.glossaryMalwareID.virusmain);
txtVirus .setText("A Computer Virus is a small peice of " +
        "Software" + just write down your link automatically converted to URL 
        "so on and so on);
Linkify.addLinks(noteView, Linkify.ALL);

阅读此LINKY FY FOR ANDROID

如果您有任何疑问,请告诉我。

于 2012-04-05T13:07:53.593 回答