在edittext中是否有獲取光標當前行的方法?如果沒有,我會寫我自己的方法,但只是想檢查。如果我寫自己的方法最好的方法是通過edittext中的每個字符,直到選擇開始並使用For循環來計數\ n的數量,還是有更好的方法?謝謝!Android:Edittext-獲取當前行
2
A
回答
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
使用方法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()
)。
我有一個演示此方法的完整工作示例,因此請告知我是否需要更多幫助。
希望這會有所幫助!
相關問題
- 1. 獲取當前行號?
- 2. 獲取當前行表ADF
- 3. DAX - 獲取當前行號
- 4. Android:Edittext充當搜索引擎
- 5. 獲取當前URL
- 6. 獲取當前MigrationId
- 7. 獲取當前URL
- 8. 獲取當前URL
- 9. 獲取當前GridView
- 10. 獲取當前UIViews?
- 11. 如何獲取當前行號?
- 12. Asp.Net GridView獲取TemplateField上的當前行
- 13. 獲取當前行的等級與Laravel
- 14. 獲取GridView的從當前行中ASP.NET
- 15. ColdFusion查詢獲取當前行值?
- 16. 運行cProfile時獲取當前模塊
- 17. SlickGrid javascript獲取當前行數據
- 18. 獲取交替行的當前列數
- 19. 野牛和rec2c:獲取當前行號
- 20. 從DataTables獲取當前行索引API
- 21. 獲取當前行文本是
- 22. 如何獲取MYSQL中當前行之前的行的總和?
- 23. Android:EditText取出剩餘空間
- 24. FreeMarker - 獲取當前URL
- 25. 獲取當前頁面(PHP)
- 26. 獲取當前座標
- 27. 獲取當前用戶名
- 28. 獲取當前列名
- 29. SceneKit:SCNPhysicsBody獲取當前速度
- 30. 獲取當前目錄
不錯,那的確更好!我沉迷於API尋找一種方法來完成這項工作,但當時沒有找到它。不過,這顯然是在API級別1之後的。 –
god work.thanks – sirmagid