天天看點

TextView添加連結

TextView添加連結

一、可行方式

java

1

2

3

4

5

6

7

8

<textview

android:id="@+id/trineainfo"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

trineainfotv = (textview)activity.findviewbyid(r.id.trineainfo);

trineainfotv.setmovementmethod(linkmovementmethod.getinstance());

spanned text = html.fromhtml("個人首頁:<a href=\"http://www.trinea.cn\"> trinea</a>");

trineainfotv.settext(text);

顯示連結樣式,能點選,touch即點選

9

10

11

12

13

14

15

16

trineainfotv.setonclicklistener(new onclicklistener() {

@override

public void onclick(view v) {

uri web = uri.parse("http://www.trinea.cn");

intent i = new intent(intent.action_view, web);

i.setflags(intent.flag_activity_new_task);

activity.startactivity(i);

}

});

顯示連結樣式,能點選。通過手動設定textview的onclicklistener完成點選響應。

android:layout_height="wrap_content"

android:autolink="all" />

trineainfotv.settext("個人首頁:http://www.trinea.cn");

顯示連結樣式,并且能點選(隻響應http://www.trinea.cn部分點選),不過不支援如下的href形式

trineainfotv.settext("個人首頁:<a href=\"http://www.trinea.cn\"> trinea</a>");

二、不可行方式

顯示連結樣式,不能點選

不顯示連結樣式,不能點選

三、通過源碼分析原因

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

if (!issuggestionunderlinerefreshflag) {

if (type == buffertype.editable || minput != null

|| neededitablefornotification) {

editable t = meditablefactory.neweditable(text);

text = t;

setfilters(t, mfilters);

inputmethodmanager imm = inputmethodmanager.peekinstance();

if (imm != null)

imm.restartinput(this);

} else if (type == buffertype.spannable || mmovement != null) {

text = mspannablefactory.newspannable(text);

} else if (!(text instanceof charwrapper)) {

text = textutils.stringorspannedstring(text);

if (mautolinkmask != 0) {

spannable s2;

if (type == buffertype.editable || text instanceof spannable) {

s2 = (spannable) text;

} else {

s2 = mspannablefactory.newspannable(text);

if (linkify.addlinks(s2, mautolinkmask)) {

text = s2;

type = (type == buffertype.editable) ? buffertype.editable : buffertype.spannable;

/*

* we must go ahead and set the text before changing the

* movement method, because setmovementmethod() may call

* settext() again to try to upgrade the buffer type.

*/

mtext = text;

// do not change the movement method for text that support text selection as it

// would prevent an arbitrary cursor displacement.

if (mlinksclickable && !textcanbeselected()) {

setmovementmethod(linkmovementmethod.getinstance());

繼續閱讀