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")
}
}
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
}
}
I try to change a public variable in kotlin but i can't. When I receive the variable in another script, it has not changed. I print the variable in the second script but then it says zero. I have no idea why. Please help me. I'm stuck. Here are my code:
package com.backal.bingolooooooooooooto
import android.content.Intent
import android.os.Bundle
import android.util.Log.d
import android.view.View
import androidx.appcompat.app.AppCompatActivity
class AddFavourActivity: AppCompatActivity() {
public var clicked = 0;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.add_favour)
val alt1: View = findViewById(R.id.alt1)
val alt2: View = findViewById(R.id.alt2)
val alt3: View = findViewById(R.id.alt3)
val alt4: View = findViewById(R.id.alt4)
val alt5: View = findViewById(R.id.alt5)
val alt6: View = findViewById(R.id.alt6)
val alt7: View = findViewById(R.id.alt7)
alt1.setOnClickListener {
var clicked = 50
startActivity(Intent(this, EnterPasswordActivity::class.java))
}
alt2.setOnClickListener {
var clicked = 80
d("Alexander", "Clicked is: $clicked")
startActivity(Intent(this, EnterPasswordActivity::class.java))
}
alt3.setOnClickListener {
startActivity(Intent(this, EnterPasswordActivity::class.java))
clicked = 100
}
alt4.setOnClickListener {
startActivity(Intent(this, EnterPasswordActivity::class.java))
clicked = 300
}
alt5.setOnClickListener {
startActivity(Intent(this, EnterPasswordActivity::class.java))
clicked = 500
}
alt6.setOnClickListener {
startActivity(Intent(this, EnterPasswordActivity::class.java))
clicked = 100
}
alt7.setOnClickListener {
startActivity(Intent(this, EnterPasswordActivity::class.java))
clicked = 1000
}
}
}
every time you are doing var clicked = 50 you're declaring a new variable (even if it's the same name) so just remove the var :
clicked = 50
something else you might want to consider is to rather make use of a companion object :
companion object {
var clicked = 0
}
then you can use this variable everywhere, by just using: AddFavourActivity.clicked
or AddFavourActivity.clicked = 50
A companion object will ensure the same instance of the variable is used everywhere
You keep creating a new variable called clicked when you do:
var clicked = 80
You should simply do:
clicked = 80
Notice I removed the var as if you don't it simply creates a new variable withing the scope of the block called clicked and it doesn't modify the global clicked variable that you created.
I'm doing a project which has a lot of buttons. I would like to iterate over those buttons by its name. They are all named 'levelXbutton', where X can be a big number.
I'm now doing it with a lot of lines of code. But I'm sure there's a way to do it in a loop, specially in Kotlin.
For example, this is one of the operations I'd like to do:
if(FacadeData.getLastUnlockedLevel()<2){ binding.lvl2Button.setTextColor(Color.WHITE)}
if(FacadeData.getLastUnlockedLevel()<3){ binding.lvl3Button.setTextColor(Color.WHITE)}
if(FacadeData.getLastUnlockedLevel()<4){ binding.lvl4Button.setTextColor(Color.WHITE)}
if(FacadeData.getLastUnlockedLevel()<5){ binding.lvl5Button.setTextColor(Color.WHITE)}
You can make a loop to go through the buttons numbers and then load their ids with a string like so:
for (i in 0..20) {
val layoutID = context.resources.getIdentifier("lvl${i}Button", "id", context.packageName)
val button = findViewById(layoutID) as Button
...
}
Maybe you should try something like this:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
applyChangeRecursively(findViewById<ViewGroup>(android.R.id.content)) {
it.setBackgroundColor(Color.WHITE)
}
}
fun getResourceName(view:View):String? {
if (view.id > 0 && view is Button) {
return view.resources.getResourceName(view.id)
}
return null
}
fun matchesLabel(resourceName:String?):Boolean = resourceName?.matches(Regex(".*lvl\\d+Button")) ?: false
fun applyChange(v:View, u:(View)->Unit) = v.run(u)
fun applyChangeRecursively(parent:View, fun1:(View)->Unit){
when (parent) {
is ViewGroup -> parent.children.forEach{ applyChangeRecursively(it, fun1) }
else -> if(matchesLabel(getResourceName(parent))) { applyChange(parent, fun1) }
}
}
}
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.