This my first kotlin/java code. I want learn from this.
When I push "OK" button of Android keyboard, I want my app do same thing as when I push my button with android:onClick="onAnswerClick"
I know my code is not very good. You can't help me to know how to optimize it
I don't know if its a good idea to learn to code on android with kotlin.
import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.*
import android.widget.AdapterView
import android.widget.Toast
import android.widget.Spinner
import kotlinx.android.synthetic.main.activity_main.*
import android.widget.EditText
class MainActivity : Activity() {
class Calculateurs{
fun aire(r: Double): Double{
return 3.141592 * r * r
}
fun circonference(r: Double): Double{
return 2.0 * 3.141592 * r
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val spinner = findViewById<Spinner>(R.id.spinner) as Spinner
// Create an ArrayAdapter using the string array and a default spinner layout
val adapter = ArrayAdapter.createFromResource(this,
R.array.mesure_array, android.R.layout.simple_spinner_item)
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
spinner.adapter = adapter
}
#SuppressLint("SetTextI18n")
fun onAnswerClick(view: View) {
val answer = (findViewById<EditText>(R.id.editText2) as EditText).text.toString()
val spinner = findViewById<View>(R.id.spinner) as Spinner
var rayon = java.lang.Double.parseDouble(answer)
if (spinner.getSelectedItem() == "Diamètre"){
rayon = rayon *2
}
if (rayon < 0) {
val toasty = Toast.makeText(applicationContext, "Ce nombre est négatif !", Toast.LENGTH_SHORT)
toasty.show()
} else if (rayon > 0) {
val c = Calculateurs()
val tc = findViewById<TextView>(R.id.cire) as TextView
tc.text = "" + c.circonference(rayon)
val ta = findViewById<TextView>(R.id.aire) as TextView
ta.text = "" + c.aire(rayon)
} else {
val toasty = Toast.makeText(applicationContext, "Ce nombre est nul !", Toast.LENGTH_SHORT)
toasty.show()
}
}
}
I think your question is how do you get your app to respond to the enter or done key when you press it in an EditText.
Since you did not show your layout, I will make a few assumptions.
Lets say you have and EditText that has the following attributes (plus others)
<EditText
android:id="#+id/field"
android:imeOptions="actionDone"
android:inputType="text"
...
app:layout_constraintTop_toTopOf="parent" />
Here is an example activity that will respond to hitting the enter key.
class MainActivity : AppCompatActivity() {
lateinit var field: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
field = findViewById(R.id.field) as EditText
}
override fun onResume() {
super.onResume()
field.setOnEditorActionListener( { textView, action, event ->
var handled = false
if (action == EditorInfo.IME_ACTION_DONE) {
println("call your method here")
handled = true
}
handled
})
}
You can call your onAnswerClick() in the location of the println("call your method here") statement, passing in textView if you like.
This example makes use of Kotlin's SAM Conversion which is covered in this section of the Kotlin documentation, specifically it uses the SAM conversion to create a TextView.OnEditorActionListener from a lambda expression
As Kamil Kulig, points out, there is definitely more samples and examples using Java than Kotlin, but I don't think you have to start with Java. You will need to learn enough Java to be able to understand what's going on in examples and documentation however.
Related
My app has 2 screens and works correctly in development so far. It already has 2 buttons ('toss' and 'startGame'which work correctly. Now I have added a further button called 'balls', designed to change the background colours of 4 TextViews ('ball1' to 'ball4'). However, pressing it once does nothing, and pressing it again causes the app to stop, with the displayed message "GC Clicker has stopped" or "GC Clicker keeps stopping".
Here is the first section of my MainActivity.kt:
package com.example.golfclicker
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.EditText
import android.widget.TextView
import android.graphics.Color
import android.widget.Button
import android.content.Intent
import android.media.AudioManager
import android.media.SoundPool
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val soundPool:SoundPool?
// Link variables to xml views
val player1Name = findViewById<EditText>(R.id.PersonName1)
val handicap1 = findViewById<EditText>(R.id.hpInput1)
val player2Name = findViewById<EditText>(R.id.PersonName2)
val handicap2 = findViewById<EditText>(R.id.hpInput2)
val startGame = findViewById<Button>(R.id.startGame)
val toss = findViewById<Button>(R.id.toss)
val bkgnd1 = findViewById<TextView>(R.id.Background1)
val bkgnd1a = findViewById<TextView>(R.id.Background1a)
val bkgnd1b = findViewById<TextView>(R.id.Background1b)
val bkgnd2 = findViewById<TextView>(R.id.Background2)
val bkgnd2a = findViewById<TextView>(R.id.Background2a)
val bkgnd2b = findViewById<TextView>(R.id.Background2b)
val balls = findViewById<Button>(R.id.balls)
val ball1 = findViewById<TextView>(R.id.ball1)
val ball2 = findViewById<TextView>(R.id.ball2)
val ball3 = findViewById<TextView>(R.id.ball3)
val ball4 = findViewById<TextView>(R.id.ball4)
var priSec = true // True:Primaries False:Secondaries
var tossedP1 = "" //String values to pass to Intent
var tossedHp1 =""
var tossedP2 = ""
var tossedHp2 =""
var tossed = false //has Toss button been used?
//Set up soundpool and load the sound file
soundPool = SoundPool(2,AudioManager.STREAM_MUSIC,0)
val sound1 = soundPool.load(baseContext,R.raw.computer_keyboard,1)
val sound2 = soundPool.load(baseContext,R.raw.coins,1)
//Handle balls button click
balls.setOnClickListener {
if(priSec==true) {
with(ball1) { setBackgroundColor(Color.parseColor("button_blue")) }
with(ball2) { setBackgroundColor(Color.parseColor("red")) }
with(ball3) { setBackgroundColor(Color.parseColor("black")) }
with(ball4) { setBackgroundColor(Color.parseColor("yellow")) }
} else {
with(ball1) { setBackgroundColor(Color.parseColor("green")) }
with(ball2) {setBackgroundColor(Color.parseColor("pink")) }
with(ball3) {setBackgroundColor(Color.parseColor("brown")) }
with(ball4) {setBackgroundColor(Color.parseColor("white")) }
}
priSec = !priSec //toggle primary/secondary
}
//Handle 'Toss' button click
toss.setOnClickListener {
var ran = (0..1).random() //Toss coin
// val ran = 1 //checking name-swapping
Any suggestions would be welcome.
Color.parseColor(...) works in different way than you think.
You can parse color like this:
Color.parseColor("#ff77bb")
In other words, you must pass hex code of color
this line is wrong .. because you didn't define the color
setBackgroundColor(Color.parseColor("button_blue")
try
setBackgroundColor(Color.parseColor("#39b8db")
or
context.getResources().getColor(android.R.color.white)
I finally found the following works to use colours defined in colors.xml.
I didn't want to include hex colours in my main code, as I may want to edit them at a later date.
ball1.setBackgroundColor(getResources().getColor(R.color.button_blue))
Thanks Niaj; this is similar to your last suggestion.
I try to learning kotlin.
I want a make a android app.
But im getting error.
i want to if i write "A" to edittext(#+id/tehlikesinifi), textview (uzmanucret) give me "40"
i write "B" to edittext(#+id/tehlikesinifi), textview (uzmanucret) give me "20"
i write "C" to edittext(#+id/tehlikesinifi), textview (uzmanucret)give me "10"
import abdullah.aydin.aykanosgb.databinding.ActivityFiyat2Binding
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class fiyat2 : AppCompatActivity() {
private lateinit var binding: ActivityFiyat2Binding
#SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityFiyat2Binding.inflate(layoutInflater)
setContentView(binding.root)
var cs= binding.calisansayisi.text.toString()
var usaat=binding.usaatucret.text.toString()
var ts=binding.tehlikesinifi.text.toString()
var uzmanucret =binding.uzmanucret.text.toString()
binding.button.setOnClickListener {
if (ts.equals( "A")){
var uzmandk =40
}else if(ts.equals("B")){
var uzmandk =20
}else if(ts.equals("C")){
var uzmandk =10
}
var uzmandk: String=""
var sonuc: String
sonuc= uzmandk
var sonuc1 = sonuc
binding.uzmanucret.text= "$sonuc"
}
}
}
You have many redundant variables which make your code messy
ts is set only once in onCreate and never get updated. To get the latest value you typed in the EditText, you should get it within the onClickListener
Kotlin control flow expression can return a value. It is more suitable to use when in your case
You don't need to call equals to compare string in Kotlin.
binding.button.setOnClickListener {
binding.uzmanucret.text = when(binding.tehlikesinifi.text.toString()){
"A" -> "40"
"B" -> "20"
"C" -> "10"
else -> null
}
}
package com.example.firstapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.EditText
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.random.Random
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val deEditText = findViewById<EditText>(R.id.de) as EditText
val ateEditText = findViewById<EditText>(R.id.ate) as EditText
Randomize.setOnClickListener{
val de = Integer.parseInt(deEditText.text.toString())
val ate = Integer.parseInt(ateEditText.text.toString())
RandomDisplay.text = (Random.nextInt(de - ate) + ate).toString()
}
}
}
I'm trying to create an app that gets two values and picks a random integer between them. I don't know what I'm doing wrong, and I really hope someone can help me. Thanks in advance.
val deEditText = findViewById<EditText>(R.id.de) as EditText
val ateEditText = findViewById<EditText>(R.id.ate) as EditText
Random.nextInt(de - ate)
if value from deEditText minus value from ateEditText is zero or negative, Radom.nextInt would throw IllegalArgumentException
// minimize the end bound to 1 by adding max()
RandomDisplay.text = (Random.nextInt(max(1, de - ate)) + ate).toString()
First, I want to say I am completely new at programming and Kotlin, I'm trying it for just 3 days now, and have no experience at all, just reading a bit about it.
I have an android device with a barcode scanner. I have made an activity with 2 edittext fields and a button. In the first edittextfield (etbc), I scan the barcode with the device, so there comes a 13 digit number in it. Next to this field I have another field, etqty, where I enter the quantity.
I'm trying to get the program to automatically set the focus to etqty, when the 13 digit number is entered in the first field.
I already tried with length, but I don't really get any result. How can I accomplish this, or do I have to use another method?
This is the code I have for now (keep in mind I'm absolutely new to this, so my code can be a bit weird and messy, but for now it does what I want it to do :-))
package com.example.project016
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import java.io.BufferedReader
import java.io.IOException
import java.io .InputStreamReader
import android.widget.Toast
import android.app.Activity
import java.io.OutputStreamWriter
import java.nio.file.StandardOpenOption
class MainActivity: AppCompatActivity () {
override fun onCreate (savedInstanceState: Bundle?) {
super.onCreate (savedInstanceState)
setContentView (R.layout.activity_main)
val etbc = findViewById (R.id.etbc) as EditText
val et1 = findViewById (R.id.et1) as EditText
val etqty = findViewById (R.id.etqty) as EditText
etbc.requestFocus()
if(fileList().contains("notes.txt")) {
try {
val file = InputStreamReader(openFileInput("notes.txt"))
val br = BufferedReader(file)
var line = br.readLine()
val all = StringBuilder()
while (line != null) {
all.append(line + "\n")
line = br.readLine()
}
br.close()
file.close()
et1.setText(all)
}
catch (e:IOException) {
}
}
val button1 = findViewById (R.id.button1) as Button
button1.setOnClickListener {
try {
val file = OutputStreamWriter(openFileOutput("notes.txt", Activity.MODE_APPEND))
file.write (etbc.text.toString() + ";" + etqty.text.toString() + "\n")
file.flush ()
file.close ()
} catch (e : IOException) {
}
Toast.makeText(this, "data were recorded", Toast.LENGTH_SHORT).show()
// finish ()
etbc.getText().clear()
etqty.getText().clear()
}
}
What you could do is to watch the text which is entered in the first field.
You could use TextWatcher for example:
etbc.addTextChangedListener(object : TextWatcher {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun afterTextChanged(s: Editable) {
if(etbc.text.length > 12) {
etqty.requestFocus()
}
}
})
Give it a try.
Btw. you could also set android:maxLength="13" in the xml
if staemnt never happening true. so please help me. i tried changing some stuff and hope it will work but it never did and only else staement is working.
package com.example.managemntsystem
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var input = editText.text
var empList = arrayListOf<String>("jacob", "raf", "boss", "john")
button.setOnClickListener {
if (input == emplist) {
textView2.setText("WORKING")
}else{
textView2.setText("Not working")
}
}
}
}
use this instead:
if (empList.contains(input.toString()))
This will check if the content of the EditText is equal to any of the list items. Remember to call toString() method when you want the EditText content.
You can also use the in operator:
if (input in empList)
if(empList.contains(input))
I think this will resolve your issue
The reason is your var input = editText.text never gets set again (even though it is a var), so in this case, It's not different from a val. You either need to reassign it or use .text directly:
Set it again:
var input = editText.text
var empList = arrayListOf("jacob", "raf", "boss", "john")
button.setOnClickListener {
input = editText.text // add this line
f (input == emplist) {
textView2.setText("WORKING")
}else{
textView2.setText("Not working")
}
}
Or not use input at all and use text itself:
button.setOnClickListener {
if (editText.text == emplist) {
textView2.setText("WORKING")
}else{
textView2.setText("Not working")
}
}