2011-10-02 82 views
2

在edittext中是否有獲取光標當前行的方法?如果沒有,我會寫我自己的方法,但只是想檢查。如果我寫自己的方法最好的方法是通過edittext中的每個字符,直到選擇開始並使用For循環來計數\ n的數量,還是有更好的方法?謝謝!Android:Edittext-獲取當前行

回答

12

只是爲了讓人們知道:

有一種更好的方式來做到這一點,然後道格·保羅通過getLineForOffset(selection)建議:

public int getCurrentCursorLine(EditText editText) 
{  
    int selectionStart = Selection.getSelectionStart(editText.getText()); 
    Layout layout = editText.getLayout(); 

    if (!(selectionStart == -1)) { 
     return layout.getLineForOffset(selectionStart); 
    } 

    return -1; 
} 
+0

不錯,那的確更好!我沉迷於API尋找一種方法來完成這項工作,但當時沒有找到它。不過,這顯然是在API級別1之後的。 –

+0

god work.thanks – sirmagid

0

使用方法lastindex = String.lastindexof(「\ n」)查找「\ n」的最後一個索引,然後使用方法String.substring(lstindex,string.length)得到一個子字符串,您將得到最後一行兩行代碼中的 。

+0

的問題是要找到當前行光標是在,但你的答案似乎並沒有解決光標的位置。 –

2

我找不到一個簡單的方法來獲取這些信息,所以你的方法似乎是正確的。不要忘了檢查,其中getSelectionStart()返回0。您可以把它在一個靜態實用方法,這樣確保代碼重用的情況:

private int getCurrentCursorLine(Editable editable) { 
    int selectionStartPos = Selection.getSelectionStart(editable); 

    if (selectionStartPos < 0) { 
     // There is no selection, so return -1 like getSelectionStart() does when there is no seleciton. 
     return -1; 
    } 

    String preSelectionStartText = editable.toString().substring(0, selectionStartPos); 
    return countOccurrences(preSelectionStartText, '\n'); 
} 

countOccurrences()方法是從this question,但你應該使用如果可行的話,該問題的更好答案之一(例如來自commons lang的StringUtils.countMatches())。

我有一個演示此方法的完整工作示例,因此請告知我是否需要更多幫助。

希望這會有所幫助!