求助android开发里,如何部分文字超链接

2025-04-07 22:11:20
推荐回答(2个)
回答1:

可以使用HTML标签的方式来实现,Android中的TextView,本身就支持部分的Html格式标签。这其中包括常用的字体大小颜色设置,文本链接等。使用起来也比较方便,只需要使用Html类转换一下即可。比如:

textView.setText(Html.fromHtml(str));


一、实现TextView里的文字有不同颜色
import android.text.Html; 

TextView t3 = (TextView) findViewById(R.id.text3); 
t3.setText(Html.fromHtml( "text3: Text with a " + "link " +"created in the Java source code using HTML.")); 


二、TextView显示html文件中的图片
我们知道要让TextView解析和显示Html代码。可以使用
Spanned text = Html.fromHtml(source); 
tv.setText(text); 
来实现,这个用起来简单方便。 
但是,怎样让TextView也显示Html中节点的图像呢? 
我们可以看到fromHtml还有另一个重构: 
fromHtml(String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler) 



实现一下ImageGetter就可以让图片显示了:
ImageGetter imgGetter = new Html.ImageGetter() { 
@Override 
public Drawable getDrawable(String source) { 
Drawable drawable = null; 
drawable = Drawable.createFromPath(source); // Or fetch it from the URL 
// Important 
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable 
.getIntrinsicHeight()); 
return drawable; 

}; 

三 TextView + HTML的应用代码

我们平常使用TextView的setText()方法传递String参数的时候,其实是调用的public final void setText (CharSequence text)方法

而String类是CharSequence的子类,在CharSequence子类中有一个接口Spanned,即类似html的带标记的文本,我们可以用它来在TextView中显示html。但在源代码上面Android源码注释中有提及TextView does not accept HTML-like formatting。


android.text.Html类共提供了三个方法,可以到Android帮助文档查看。

public static Spanned fromHtml (String source)

public static Spanned fromHtml (String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)

public static String toHtml (Spanned text)



通过使用第一个方法,可以将Html显示在TextView中:

public void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.main);  

  

        TextView tv=(TextView)findViewById(R.id.textView1);  

        String html="TextView使用HTML

强调

斜体

"  

                +"

超链接HTML入门学习HTML!

颜色1"  

                +"

颜色2

标题1

标题2

标题3

大于>小于<

" +  

                "下面是网络图片

";            

        tv.setMovementMethod(ScrollingMovementMethod.getInstance());//滚动  

        tv.setText(Html.fromHtml(html));      

    }  


效果: 

可以看出,字体效果是显示出来了,但是图片却没有显示。要实现图片的显示需要使用Html.fromHtml的另外一个重构方法:public static Spanned fromHtml (String source, Html.ImageGetterimageGetter, Html.TagHandler tagHandler)其中Html.ImageGetter是一个接口,我们要实现此接口,在它的getDrawable(String source)方法中返回图片的Drawable对象才可以。

回答2:

text.setText("点击上面的“下一步”按钮,即表示你同意");
text.append(Html.fromHtml(""+"《XXX条款和服务协议》"+" "));
这样写就可以了