Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v7.widget.SearchView
android:id="@+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:iconifiedByDefault="false" />
<TextView
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:textColor="@android:color/holo_red_dark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/occurrenceTextView"/>
<ScrollView
android:clipToPadding="true"
android:layout_margin="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:textAppearance="@style/TextAppearance.AppCompat.Body1"
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
import android.app.Activity
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.support.v7.widget.SearchView
import android.text.SpannableString
import android.text.style.BackgroundColorSpan
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import android.text.Spanned
class MainActivity : Activity() {
lateinit var data: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
data = getString(R.string.data)
textView.text = data
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String): Boolean {
highlightText(newText)
return false
}
})
occurrenceTextView.paintFlags = Paint.UNDERLINE_TEXT_FLAG
}
private fun highlightText(s: String) {
var occurrence = 0
val spannableString = SpannableString(textView.text)
val backgroundColorSpans =
spannableString.getSpans(0, spannableString.length, BackgroundColorSpan::class.java)
backgroundColorSpans.forEach { spannableString.removeSpan(it) }
var index = spannableString.toString().indexOf(s)
while (index > 0) {
occurrence += 1
spannableString.setSpan(BackgroundColorSpan(Color.GREEN), index,
index + s.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
index = spannableString.toString().indexOf(s, index + s.length)
}
textView.text = spannableString
occurrenceTextView.text = "this word occurred $occurrence times"
}
private fun Any.log() =
Log.d("MEGA", this.toString())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment