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
}
}
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.
So this is the button I am referring to:
<Button
android:id="#+id/btnBR"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="4dp"
android:layout_marginEnd="4dp"
android:backgroundTint="#e6ebf2"
android:onClick="setLetter"
app:layout_constraintBottom_toBottomOf="#+id/btnBM"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/btnBM"
app:layout_constraintTop_toBottomOf="#+id/btnMR" />
In my MainActivity file I am trying to create a function that will change the text of the button clicking on it. I have 9 different buttons(trying to make a tic tac toe game) that all will need the same functionality.
package brianmason.example.tictactoe
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import brianmason.example.tictactoe.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
fun setLetter(view: View){
//Trying to do the equivalent of this.setText("X") however this seems to be referring to the MainActivity and not the view. view.setText("X") also does not work.
}
}
What can I do to refer to the button that is being clicked on when using the setText function?
Declare a variable private var player1Turn = true, we'll use this variable to check whose turn is it and accordingly we mark "X" and "O" on the button.
Set onClickListner on each button as follows
binding.button1.setOnClickListner{
if(button1.text != "") return#setOnClickListener
else if(player1Turn) {
button1.text = "X"
player1Turn = !player1turn
}
else {
button1.text = "O"
player1Turn = !player1turn
}
}
Note: I am using "X" for player 1 and "O" for player 2.
Let me know if it works.
What you can do is to cast the view as a Button and then set the text.
Like this:
fun setLetter(view: View){
(view as Button).text = "X"
}
Alternatively, this is what you can do. Inside your xml layout, change the onClick attribute in all your buttons to the following and add a data tag:
<data>
<variable name="mainViewModel"
type="com.example.yourappname.MainViewModel"/> <!-- The path to your ViewModel class>
</data>
<!-- The parameter of handleClick function takes a value to identify each button. Makes sure it is unique for each button -->
<Button
...
<!--The 1 donates the unique parameter to identify the button -->
android:onClick='#{() -> mainViewModel.handleClick("1")}'/>
<Button
...
android:onClick='#{() -> mainViewModel.handleClick("2")}'/>
Then create a ViewModel to handle the clicks:
class MainViewModel: ViewModel() {
//private data so that we can only modify it inside this class
private val _buttonText = MutableLiveData<String>()
//exposable data so that we can observe its changes later
val buttonText = _buttonText as LiveData<String>
/**
*This is the function that will handle the clicks from the layout
**/
fun handleClick(string: String) {
when (string) {
// the value for buttonText can be anything here
"1" -> _buttonText.value = "Button One clicked" //Can be "X"
"2" -> _buttonText.value = "Button Two clicked" //Can be "O"
"3" -> _buttonText.value = "Button Three clicked" //etc
"4" -> _buttonText.value = "Button Four clicked"
...
...
}
}
}
Now inside your onCreate method in your MainActivity, add the following
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this#MainActivity, R.layout.activity_main)
//Get the ViewModel
val mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
binding.mainViewModel = mainViewModel //Bind the ViewModel
binding.lifecycleOwner = viewLifecycleOwner //Set the lifecycleOwner
//Observe the change made to the buttonText in the ViewModel and display its value as a Toast
mainViewModel.buttonText.observe(viewLifecycleOwner, {
Toast.makeText(this#MainActivity, it, Toast.LENGTH_SHORT).show()
//You can also modify the button text here
})
}
}
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.
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")
}
}
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.