2011-12-11 49 views
1

使用StaticLayout將HTML中的文本繪製到畫布上。 我需要弄清楚的是,我可以如何在文本中點擊鏈接。 我認爲最簡單的方法是獲取文本中鏈接的座標,並在視圖上使 爲自定義點擊事件。獲取靜態佈局中鏈接的位置

這是我的神至今:

Spanned mySpannedHTML = Html.fromHtml(html_text, null, null); 

StaticLayout sl = new StaticLayout(mySpannedHTML, mWhite, mWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); 

sl.draw(canvas); 

//FINE SO FAR, but how to get the coorinates of the links? 


//GETTING THE LINKS 

URLSpan[] getUrls =((Spanned) sl.getText()).getSpans(0, sl.getText().length(), URLSpan.class); 

for (URLSpan urlSpan : getUrls) { 

       int start =((Spanned) sl.getText()).getSpanStart(urlSpan); 
       int end =((Spanned) sl.getText()).getSpanEnd(urlSpan); 

//LOG LINKS URL AND LINK TEXT 

       Log.i("spans", "url: "+urlSpan.getURL() + " Link text: "+ ((Spanned) sl.getText()).subSequence(start, end) + " "); 

      } 

所以,我在這裏很堅持......我之所以需要在文本中的鏈接的座標,是因爲我加載到畫布上一個用於渲染的openGL紋理。說得通?

回答

4

我創建了一個函數來傳遞調用者的MotionEvent和View。然後,我得到了urlSpan的路徑,獲取邊界(參見rectF)並將該偏移量添加到矩形中(因爲我的staticlayout沒有覆蓋整個屏幕,並且rectF顯示了靜態佈局中的位置) rectF給出URLSpan的界限。

public boolean onTextTouched(View widget,MotionEvent event) 
{ 
    //If the text contains an url, we check its location and if it is touched: fire the click event. 
    Spanned spanned = (Spanned)text; 
    URLSpan[] urls = spanned.getSpans(0,spanned.length(),URLSpan.class); 
    for(int i=0;i<urls.length;i++) 
    { 
     //get the start and end points of url span 
     int start=spanned.getSpanStart(urls[i]); 
     int end=spanned.getSpanEnd(urls[i]); 

     Path dest = new Path(); 
     mStaticLayout.getSelectionPath(start, end, dest); 

     RectF rectF = new RectF(); 
     dest.computeBounds(rectF, true); 

     //Add the left and top margins of your staticLayout here. 
     rectF.offset(getContentLeft(),getContentTop()); 

     if(rectF.contains(event.getX(),event.getY())) 
     { 
      urls[i].onClick(widget); 
      return true; 
     } 
    } 
    return false; 
} 
+0

工程就像一個魅力!謝謝! –

0

使用paint並使用measureText來確定x座標,然後使用行號和上升和下降來確定y's。