Mobile App Dev 2022W: Tutorial 6
In this tutorial you will be playing with textanalyzer-5, which implements the same text analyzer functionality as Tutorial 2's textanalyzer-1, [Mobile App Dev 2022W: Assignment 1|Assignment 1's textanalyzer-2], and Tutorial 5. This version, however, is an Android app.
Getting Started
textanalyzer-5 Code
MainActivity.kt
package carleton.comp1601.textanalyzer5
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.widget.PopupMenu
import kotlin.reflect.KFunction1
class MainActivity : AppCompatActivity() {
private lateinit var t: EditText
private lateinit var analysisResult: TextView
var analysisMode = "None"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
t = findViewById(R.id.t)
t.addTextChangedListener(twatcher)
analysisResult = findViewById(R.id.analysisResult)
updateAnalysis()
}
fun onMenuItemClick(choice: MenuItem): Boolean {
analysisMode = choice.getTitle() as String
updateAnalysis()
return true
}
// https://stackoverflow.com/questions/15580111/
fun showMenu(v: View) {
val menu = PopupMenu(this, v)
for (s in analysis.keys) {
menu.menu.add(s)
}
menu.setOnMenuItemClickListener(::onMenuItemClick)
menu.show()
}
private val twatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable) {
updateAnalysis()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
}
fun updateAnalysis() {
val inputText: Editable? = t.text
if (inputText != null) {
val analysisFunc: KFunction1<String, String>? = analysis[analysisMode]
if (analysisFunc != null) {
val r = analysisFunc(inputText.toString())
analysisResult.setText(analysisMode + ": " + r)
} else {
analysisResult.setText("Please choose an analysis mode.")
}
}
}
}
fun countUpper(s: String): String {
var count = 0
val upperCase = setOf("A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z")
for (c in s) {
if (upperCase.contains(c.toString())) {
count += 1
}
}
return count.toString()
}
fun countCharacters(s: String): String {
val charcount = s.length
return charcount.toString()
}
val analysis: MutableMap<String, KFunction1<String, String>> = mutableMapOf(
"Count" to ::countCharacters,
"Upper Case" to ::countUpper
)