Android Kotlin cannot change a text string within a function - android

I have some really simple Kotlin code for changing a text string within a function generated from a button press, but it does not work. I have a single button and two text strings, one the button press the first text string changes but the text string within the function does not change.
I am sure the problem is with the function call and not passing the right information about the activity, but just cannot work out what is wrong.
MainActivty.kt
package com.example.sandpit9
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*
import org.w3c.dom.Text
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageButton1.setOnClickListener {v: View -> toast(v) }
imageButton1.setOnClickListener {
imageButton1.setImageResource(R.drawable.greenbutton)
textView1.text = "1234"
}
}
public fun toast(v: View) {
v.textView2.text = "1234"
}
}
MainActivty.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/imageButton1"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:textSize="34sp"/>
<TextView
android:text="textvar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:textSize="34sp"
android:layout_marginTop="108dp"
app:layout_constraintTop_toBottomOf="#+id/imageButton1"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintHorizontal_bias="0.535"/>
<ImageButton
android:layout_width="174dp"
android:layout_height="154dp"
app:srcCompat="#drawable/download"
android:id="#+id/imageButton1"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.542"
app:layout_constraintVertical_bias="0.187"/>
</android.support.constraint.ConstraintLayout>

You're overwriting the click listener. The OnClickListener is a single property - not a list.
imageButton1.setOnClickListener {v: View ->
toast(v)
imageButton1.setImageResource(R.drawable.greenbutton)
textView1.text = "1234"
}

imageButton1.setOnClickListener {v: View -> toast(v) }
imageButton1.setOnClickListener {
imageButton1.setImageResource(R.drawable.greenbutton)
textView1.text = "1234"
}
Problem: ImageButton have only one OnClickListener to listen the event when there is a click event on it own. You can set the listener by using setOnClickListener. Because in your code, you use setOnClickListener two times, so the second one will override the first one.
Solution: Change your code to
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageButton1.setOnClickListener {
imageButton1.setImageResource(R.drawable.greenbutton)
textView1.text = "1234"
textView2.text = "1234"
}
}
}

Many thanks, how simple is the solution many thanks for all the help, the setOnClickListener is setup only once to trigger the function. This is the finial code that works
package com.example.sandpit9
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*
import org.w3c.dom.Text
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageButton1.setOnClickListener{v: View -> toast(v)}
}
private fun toast(v: View) {
imageButton1.setImageResource(R.drawable.greenbutton)
textView1.text = "1234"
textView2.text = "1234"
}
}

remove this import
import kotlinx.android.synthetic.main.activity_main.view.*
Hope this will work

Related

(Android) On checkbox unchecked/checked, the cursor in edit text shifts to initial position when used to hide/show password

I am using a checkbox to toggle password visibility in edit text. Basically, when I check/uncheck the checkbox, the cursor of the edit text shifts to the initial position of the character in the password text. It should not change the cursor position in edit text when the checkbox is checked or unchecked.
Please anyone can suggest why the cursor position changes? and how I can fix that?
login_layout
<?xml version="1.0" encoding="utf-8"?>
<layout>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<EditText
android:id="#+id/etUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:autofillHints="name"
android:hint="Username"
android:imeOptions="actionNext"
android:inputType="text"
android:maxLines="1"
android:padding="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:autofillHints="password"
android:hint="Password"
android:imeOptions="actionDone"
android:inputType="textPassword"
android:maxLines="1"
android:padding="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etUsername" />
<CheckBox
android:id="#+id/imgTogglePassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="-5dp"
android:layout_marginEnd="-5dp"
android:button="#drawable/btn_toggle_password"
android:padding="16dp"
app:layout_constraintBottom_toBottomOf="#id/etPassword"
app:layout_constraintEnd_toEndOf="#id/etPassword"
app:layout_constraintTop_toTopOf="#id/etPassword" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
LoginActivity
import android.os.Bundle
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.testapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
initUI()
}
private fun initUI() {
binding.imgTogglePassword.setOnCheckedChangeListener { _, isChecked ->
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// hide password
binding.etPassword.transformationMethod = PasswordTransformationMethod.getInstance()
} else {
// show password
binding.etPassword.transformationMethod = HideReturnsTransformationMethod.getInstance()
}
}
}
}
Login Page
Issue
You just need to use this line :
binding.etPassword.setSelection(binding.etPassword.text.length) as the below code.
import android.os.Bundle
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.testapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
initUI()
}
private fun initUI() {
binding.imgTogglePassword.setOnCheckedChangeListener { _, isChecked ->
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// hide password
binding.etPassword.transformationMethod = PasswordTransformationMethod.getInstance()
} else {
// show password
binding.etPassword.transformationMethod = HideReturnsTransformationMethod.getInstance()
}
binding.etPassword.setSelection(binding.etPassword.text.length)
}
}
}
CheckBox is not the common way to show/hide password.
Try endIconDrawable:
<com.google.android.material.textfield.TextInputLayout
...
app:endIconDrawable="#drawable/selector_button_eye"
app:endIconCheckable="true"
app:endIconTint="#color/colorEyeButtonTint">
<com.google.android.material.textfield.TextInputEditText
...
android:inputType="textPassword" />
</com.google.android.material.textfield.TextInputLayout>
I' m not sure about the "endIconXXX" attributes because I only used the deprecated passwordToggleDrawable before. But they are similar.

Changing text value with Kotlin in Android Studio

New to Kotlin, I've followed the guide on how to set up a basic "Press the button and it changes text" However Whenever I press the button, the app crashes and in the debugger I get
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)'
on a null object reference at com.example.myapplication.MainActivity.One(MainActivity.kt:16)
Here is my current MainActivity.KT:
package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun One(view: android.view.View) {
val onetext = view.findViewById<TextView>(R.id.textView)
onetext.text = "Hello"
}
}
And my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="168dp"
android:layout_height="90dp"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="One"
android:text="Button"
tools:layout_editor_absoluteX="163dp"
tools:layout_editor_absoluteY="462dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Thank you!
The problem is onetext is null, which means view.findViewById<TextView>(R.id.textView) didn't find a view with textView as id inside of view. The view passed in the function is the button, which has no textView as a child. You need to search for the textView in a view higher in the hierarchy.
In the specific example, one way of doing that is by omitting the view receiver, like so:
package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun One(view: android.view.View) {
val onetext = findViewById<TextView>(R.id.textView)
onetext.text = "Hello"
}
}
This way it will search for the textView id in the Activity's view, which is the activity_main layout.
I believe the problem has already been solved, but I noticed that in the xml file the button is not properly docked, putting:
app:layout_constraintTop_toBottomOf="#id/textView"
the button would be below the TextView component and putting:
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
the button would be centered on the screen...
Button code would look like this
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="One"
android:text="Button"
app:layout_constraintTop_toBottomOf="#id/textView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"/>

Android - DialogFragment doesn't show the ImageView that I put into it

I faced an error that actually mustn't occur, because I do exactly the same thing in my project in another screen, and it works there, but doesn't want to work in another screen.
The problem is the following: from an Activity in a result of some action I open up a DialogFragment which contains an image and other views in its layout file. Now I can't understand why, but it works in the first case (you'll see below) but doesn't work in the second...
First case:
Layout XML file (dialog_character_selector.xml):
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="dialogViewModel"
type="neptun.jxy1vz.cluedo.ui.menu.character_selector.CharacterSelectorViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:id="#+id/spinnerCharacter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/ivCharacterCard"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="20dp"
android:src="#drawable/szereplo_hatlap"
app:layout_constraintBottom_toTopOf="#+id/btnStart"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent="0.7"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/spinnerCharacter" />
<Button
android:id="#+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/start"
android:layout_marginBottom="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:onClick="#{()->dialogViewModel.startGame()}"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
The DialogFragment's Kotlin source code (CharacterSelectorDialog.kt):
package neptun.jxy1vz.cluedo.ui.menu.character_selector
import android.animation.AnimatorInflater
import android.animation.AnimatorSet
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.app.AlertDialog
import androidx.core.animation.doOnEnd
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import neptun.jxy1vz.cluedo.R
import neptun.jxy1vz.cluedo.databinding.DialogCharacterSelectorBinding
class CharacterSelectorDialog : DialogFragment(), AdapterView.OnItemSelectedListener {
private lateinit var dialogCharacterSelectorBinding: DialogCharacterSelectorBinding
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
dialogCharacterSelectorBinding = DataBindingUtil.inflate(
LayoutInflater.from(context),
R.layout.dialog_character_selector,
null,
false
)
dialogCharacterSelectorBinding.spinnerCharacter.adapter = ArrayAdapter<String>(
context!!,
android.R.layout.simple_spinner_dropdown_item,
resources.getStringArray(R.array.characters)
)
dialogCharacterSelectorBinding.spinnerCharacter.onItemSelectedListener = this
//I do this due to a card flipping animation, it's not important, not part of my problem
val scale = resources.displayMetrics.density
dialogCharacterSelectorBinding.ivCharacterCard.cameraDistance = 8000 * scale
dialogCharacterSelectorBinding.dialogViewModel = CharacterSelectorViewModel(context!!)
return AlertDialog.Builder(context!!, R.style.Theme_AppCompat_Light_Dialog).setView(dialogCharacterSelectorBinding.root).setTitle(resources.getString(R.string.dialog_character_title)).create()
}
override fun onNothingSelected(parent: AdapterView<*>?) {
dialogCharacterSelectorBinding.ivCharacterCard.setImageResource(R.drawable.szereplo_hatlap)
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
dialogCharacterSelectorBinding.ivCharacterCard.setImageResource(R.drawable.szereplo_hatlap)
(AnimatorInflater.loadAnimator(context, R.animator.card_flip) as AnimatorSet).apply {
setTarget(dialogCharacterSelectorBinding.ivCharacterCard)
start()
doOnEnd {
dialogCharacterSelectorBinding.dialogViewModel!!.setPlayer(position)
val img = when (position) {
0 -> R.drawable.szereplo_ginny
1 -> R.drawable.szereplo_harry
2 -> R.drawable.szereplo_hermione
3 -> R.drawable.szereplo_ron
4 -> R.drawable.szereplo_luna
else -> R.drawable.szereplo_neville
}
dialogCharacterSelectorBinding.ivCharacterCard.setImageResource(img)
}
}
}
}
Second case:
Layout XML file (dialog_helper_card.xml):
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="helperCardDialogViewModel"
type="neptun.jxy1vz.cluedo.ui.dice.card_dialog.helper.HelperCardViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/ivHelperCard"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="20dp"
android:src="#drawable/mento_hatlap"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
I think in the main parts it's just the same as the previous one.
Kotlin source file (HelperCardDialog.kt):
package neptun.jxy1vz.cluedo.ui.dice.card_dialog.helper
import android.animation.AnimatorInflater
import android.animation.AnimatorSet
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import androidx.core.animation.doOnEnd
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import neptun.jxy1vz.cluedo.R
import neptun.jxy1vz.cluedo.databinding.DialogHelperCardBinding
class HelperCardDialog(private val cardResource: Int) : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): AlertDialog {
val dialogHelperCardBinding = DataBindingUtil.inflate<DialogHelperCardBinding>(LayoutInflater.from(context), R.layout.dialog_helper_card, null, false)
dialogHelperCardBinding.helperCardDialogViewModel = HelperCardViewModel()
(AnimatorInflater.loadAnimator(context, R.animator.card_flip) as AnimatorSet).apply {
setTarget(dialogHelperCardBinding.ivHelperCard)
start()
doOnEnd {
dialogHelperCardBinding.ivHelperCard.setImageResource(cardResource)
}
}
return AlertDialog.Builder(context!!, R.style.Theme_AppCompat_Dialog).setTitle(resources.getString(R.string.got_helper_card)).setNeutralButton(resources.getString(R.string.ok)
) { dialog, _ ->
dialog.dismiss()
}.create()
}
}
That's it. These are my most important files in my problem. Sorry for the lot of code...
I hope you will see where the problem is and tell me what's the solution for it.
Finally I found the error in my code. I left the setView() function call from the second AlertDialog.Builder().
The correct code snippet is:
return AlertDialog.Builder(context!!, R.style.Theme_AppCompat_Dialog)
.setView(dialogHelperCardBinding.root)
.setTitle(resources.getString(R.string.got_helper_card)).setNeutralButton(
resources.getString(R.string.ok)
) { dialog, _ ->
dialog.dismiss()
}.create()

Android Button setOnClickListener call function to change button image

I have an app with multiple buttons and the image will change depending on different requirements and variables. But, I cannot get the image button change to work within the function. The setOnClickListner will setup the function call and within the function will change the image within the button.
How do I change the image in the button?
MainActivity.kt
package com.example.sandpit9
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)
imageButton1.setOnClickListener() { changeimageelement1(R.drawable.button) }
imageButton2.setOnClickListener() { changeimageelement2(R.drawable.button) }
}
}
private fun changeimageelement1(imageButtonX: Int) {
imageButton1.setImageResource(R.drawable.greenbutton)
}
MainActivity.xml
<?xml version="1.0" encoding="utf-8">
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageButton
android:layout_width="174dp"
android:layout_height="154dp" app:srcCompat="#drawable/download"
android:id="#+id/imageButton1"
app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp" android:layout_marginRight="8dp"
app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="8dp"
android:layout_marginStart="8dp" android:layout_marginTop="8dp" app:layout_constraintTop_toTopOf="parent"
android:layout_marginBottom="8dp" app:layout_constraintBottom_toBottomOf="parent"/> .
</android.support.constraint.ConstraintLayout>
you should not use the () after setOnClickListener, just use
button.setOnClickLisener{
//your actions go here
}
ClickListener method should besetOnClickListener not setOnClickListener
A sample code:
button.setOnClickListener{
counter++
textView.text = "Click counter : $counter"
}
Check this tutorial

android kotlin - app keep keeps stopping when i click the button

I start doing a simple android app for practice to calculate the age with Kotlin programming language, when i click the button the app, can someone help me with this and fix it to know where is my wrong because I am just very beginner
package com.calcult.age.agecalcult
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var ageInput = ageText.text.toString()
doIT.setOnClickListener{
var currentYear = Calendar.getInstance().get(Calendar.YEAR)
var getAge = currentYear-ageInput.toInt()
Toast.makeText(this, getAge, Toast.LENGTH_LONG)
}
}
}
XML FILE :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginEnd="148dp"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="148dp"
android:id="#+id/doIT"
android:text="#string/button_text1"
android:textSize="18sp"
app:layout_constraintHorizontal_bias="0.0" android:layout_marginTop="8dp"
app:layout_constraintTop_toTopOf="parent" android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintVertical_bias="0.771"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/ageText" app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="215dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="85dp"
app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="84dp"
android:layout_marginBottom="250dp" app:layout_constraintBottom_toTopOf="#+id/doIT"/>
</android.support.constraint.ConstraintLayout>
As Vladyslav Matviienko said you're trying to get the text onCreate, what you need to do is something like this:
//Here the view is already created, so you'll be able to setup everything you need.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupListener()
}
//If you are learning, you should consider reading a bit about clean code,
//it's always nice that a function does just one job, that's why I broke the code
//below in two little functions. Have in mind, this code is not the best, but at the
//moment i don't have much time to write this.
private fun setupListener() {
doIT.setOnClickListener{
//Always be aware of the type of the variables, when i wrote the first answer i was
//trying to do a math operatiton using a string, so it would not work. =P
var currentYear = Calendar.getInstance().get(Calendar.YEAR)
var getAge = (currentYear-getAge().toInt()).toString()
Toast.makeText(this, getAge, Toast.LENGTH_LONG).show()
}
}
private fun getAge(): String {
return ageText.text.toString
}

Categories

Resources