티스토리 뷰
리스트를 검색할 때 실시간으로 해당 검색어에 해당하는 목록을 보여주며
리스트에 있는 문자열에 검색어를 하이라이트 처리 해야할 경우가 있다.
리컬시브 동작으로 간단하게 짜 보았다.
private fun startSearchHighlight(tv: TextView, fullString: String, searchString: String, isCaseSensitive: Boolean) {
var fullStr: String = fullString
var searchStr: String = searchString
if( !isCaseSensitive ) { // 대소문자 구분 필요없을 때
fullStr = fullString.lowercase(Locale.US)
searchStr = searchString.lowercase(Locale.US)
}
val startIdx: Int = fullStr.indexOf(searchStr)
if (startIdx == -1 || searchString.isBlank() ) {
// 검색어가 없거나 일치하는 결과가 없을 경우 원래 색으로 원복
tv.text = fullString
return
}
val sp: Spannable = SpannableString(fullString)
val endIdx = startIdx + searchString.length
val colorValue = // 원하는 컬러 값 세팅
// 재귀함수로 해당 문자열에서 검색어 찾기
recursiveSpannable(fullString, searchString, sp, startIdx, endIdx, colorValue, isCaseSensitive)
tv.text = sp
}
private fun recursiveSpannable(fullString: String, searchString: String, sp: Spannable, startIdx: Int, endIdx: Int, colorValue: Int, , isCaseSensitive: Boolean) {
var fullStr: String = fullString
var searchStr: String = searchString
if( !isCaseSensitive ) { // 대소문자 구분 필요없을 때
fullStr = fullString.lowercase(Locale.US)
searchStr = searchString.lowercase(Locale.US)
}
val subStartIdx: Int = fullStr.indexOf(searchStr, endIdx)
if (startIdx != -1) {
val subEndIdx: Int = subStartIdx + searchString.length
recursiveSpannable(fullString, searchString, sp, subStartIdx, subEndIdx, colorValue, isCaseSensitive)
sp.setSpan(ForegroundColorSpan(colorValue), startIdx, endIdx, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
'Android Memo' 카테고리의 다른 글
[Android] 도메인에서 해당 SSL 공개키 가져오는 방법 (0) | 2024.08.06 |
---|---|
Android Double Click 기능 구현 (2) | 2024.08.06 |
Installed Build Tools revision 31.0.0 is corrupted (0) | 2022.06.21 |
EditText Custom Background 지정 (0) | 2020.06.23 |
반복문으로 문자열을 합칠 때 생기는 Warning 관련... (0) | 2019.01.17 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- android o
- glide
- notification
- buildToolsVersion 31.0.0
- AnimationDrawable
- targetSdkVersion 31
- String append
- FrameAnimation
- Android Custom Dialog
- ViewPager
- startForegroundService
- fontFamily
- 문자열
- Android 더블 클릭
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
글 보관함