I am trying to add numbers with 3 EditTexts and I want to display it on text view with a calculate button but there's something wrong with Kotlin code as I'm newbie
Here's my code:
class Add : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_adsense)
var input_num1 = num1
var input_num2 = numm2
var input_num3 = num3
result.setOnCLickListener {
var result = input_num1.toStrubg()?.toLong() + input_num2.toStrubg()?.toLong() + input_num3.toLong()?.toString()
}
}
}
<TextView
android:id="#+id/textView"
android:textSize="20dp" />
<EditText
android:id="#+id/num1"
android:inputType="number" />
<TextView
android:id="#+id/textView2"
android:textSize="20dp" />
<EditText
android:id="#+id/num2"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/textView3"
android:textSize="20dp" />
<EditText
android:id="#+id/num3"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/result"
android:textSize="20dp"
android:text="Result" />
<Button
android:id="#+id/Calculate"
android:onClick="Calculate"
android:text="Calculate"
android:textSize="20dp" />
You say you are a newbie but that doesn't mean you will have to ignore the compiler or IDE errors. Clearly toStrubg() is not a keyword and your IDE will make you aware of that. Don't know what the rest of your code looks like so will help you with the result.setOnClickListener.
Try this
result.setOnClickListener {
var result = input_num1.toString()?.toLong() + input_num2.toString()?.toLong() + input_num3.toString()?.toLong()
}
Also I'll advise that you should try and learn Kotlin first before embarking on your Android development journey. Here are some links to help you.
Docs
try
Related
I'm writing a simple tip calculator app in android studio ( which is one of the programs in the https://developer.android.com/courses/android-basics-kotlin/course course ).
But I'm getting an unexpected error, unresolved reference: toDouble, when I try to covert a string to a double. Even after pasting the solution code from the website into my application, the error won't go away. I also tried first converting the string to an int using toInt function but I get the same error.
Here is the code inside MainActivity.kt.
package com.example.tiptime
import java.text.NumberFormat
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.tiptime.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.calculateButton.setOnClickListener{ calculateTip() }
}
fun calculateTip() {
val stringInTextField = binding.costOfService.text.toString()
val cost = stringInTextField.toDouble()
}
}
Here is my code in 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"
android:padding="16dp"
tools:context=".MainActivity"
tools:ignore="UseSwitchCompatOrMaterialXml">
<EditText
android:id="#+id/cost_of_service"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:hint="#string/cost_of_service"
android:inputType="numberDecimal"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:autofillHints="#string/cost_of_service" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/how_was_the_service"
android:id="#+id/service_question"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/cost_of_service"/>
<RadioGroup
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/tip_options"
android:checkedButton="#+id/option_twenty_percent"
app:layout_constraintTop_toBottomOf="#id/service_question"
app:layout_constraintStart_toStartOf="parent">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/option_twenty_percent"
android:text="#string/amazing_20"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/option_eighteen_percent"
android:text="#string/great_18"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/option_fifteen_percent"
android:text="#string/ok_15"/>
</RadioGroup>
<Switch
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/round_up_switch"
android:text="#string/round_up_tip"
android:checked="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/tip_options" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/calculate"
android:id="#+id/calculate_button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#id/round_up_switch"
/>
<TextView
android:id="#+id/tip_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tip_amount"
app:layout_constraintTop_toBottomOf="#id/calculate_button"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
And here is the screenshot of the error
Any help is appreciated!!
Seems like you do not have the latest kotlin support .
Update the Kotlin version to the latest one from :
File ->> Setting -->> Language & Frameworks -->> Kotlin ...
Try after removing
import java.text.NumberFormat
comment
fun calculateTip() {
val stringInTextField = binding.costOfService.text.toString()
val cost = stringInTextField.toDouble()
}
build & clean
uncomment the code in above method you will get correct import
Use
val cost = Double.parseDouble(stringInTextField)
I want to take Input from user(their name) with editableText just like the below video(watch at 8:24). But, I am not able to take input because android studio is not recognizing "editableText". Am i missing something?
Android Development Tutorial Video at 8:24
Error ->>
Unresolved reference: nameInput [In the below MainActivity.kt]
MainActivity.kt
package com.example.firstapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun createBirthdayCard(view: View){
val name = nameInput.**editableText**.toString() <-- [error is in this line]
}
}
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/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="140dp"
android:text="Enter Name"
android:textColor="#000000"
android:textSize="50sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:textAlignment="center" />
<EditText
android:id="#+id/nameInput"
android:layout_width="280dp"
android:layout_height="54dp"
android:layout_marginTop="64dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
android:textSize="25sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3"
tools:textAlignment="center" />
<Button
android:id="#+id/createBirthdayCard"
android:layout_width="307dp"
android:layout_height="81dp"
android:layout_marginTop="144dp"
android:maxLines="1"
android:text="Create Birthday Card"
android:textSize="19sp"
android:onClick="createBirthdayCard"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/nameInput"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
:) :) Thanks for spending your valuable time to help me :) :)
Android kotlin extensions removed at Android studio 4.1V.
I recommend use the ViewBinding or DataBinding.
This is a good reference.
https://android-developers.googleblog.com/2020/11/the-future-of-kotlin-android-extensions.html
ViewBinding : https://developer.android.com/topic/libraries/view-binding?hl=ko
DataBinding : https://developer.android.com/topic/libraries/data-binding
As Android kotlin extensions is deprecated and removed you may use
View binding, Data binding as suggested by Seungho Kang
OR you can declare variable as shown below.
fun createBirthdayCard(view: View){
val editText=findViewById<EditText>(R.id.nameInput)
val name = editText.editableText.toString()
}
Following is my current solution:
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onCheckedChanged="#{(group, buttonId) -> student.setGenderIndex(group.indexOfChild(group.findViewById(buttonId)))}"
android:orientation="horizontal">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:checked="#{student.genderIndex == 0}"
android:text="Male" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="#{student.genderIndex == 1}"
android:text="Female" />
</RadioGroup>
This works fine, but I'm wondering if there is a better way to do this. And then I find out that there is a built-in two-way attribute for RadioGroup: android:checkedButton (from Official Documentation), however it is the id not the index I want:
public static final int checkedButton
The id of the child radio button that should be checked by default within this radio group.
May be an integer value, such as "100".
Constant Value: 16843080 (0x01010148)
I still try (to make my binding expression shorter) but doesn't work:
android:onCheckedChanged="#{(group, buttonId) -> student.setGenderIndex(group.indexOfChild(group.checkedButton))}"
Says "Could not find accessor android.widget.RadioGroup.checkedButton"
Add onCheckedChanged like this
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onCheckedChanged="#{vm.onSplitTypeChanged}">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/email" />
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sms" />
</RadioGroup>
Then in your view model implement onSplitTypeChanged like this
fun onSplitTypeChanged(radioGroup: RadioGroup?, id: Int) {
val checked = radioGroup?.findViewById<RadioButton>(id)
val index = radioGroup?.indexOfChild(checked)
}
I am a student and I am currently building an Android application with Kotlin as the programming language. The application's aim will be to register keystrokes from users which I will use for biometric research purpose. I am not proficient in Kotlin or Android Studio as this is the first time I am working in Android Studio.
The application has many activities and I am sharing the code from one of the activities, where I need to recognize the keystrokes in Editexts, while the user presses keys in soft keyboard to type username and password.
I found some Android Developers examples about KeyEvents and some References.
The data I need from the keystrokes are as follows:
a. the key pressed.
b. key pressed time.
c. key released time.
d. its ASCII value.
The XML Code is as follows:
<Button
android:id="#+id/button5"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="#drawable/rounded_button"
android:fontFamily="#font/pt_mono"
android:onClick="resetval"
android:text="#string/reset"
android:textAlignment="center"
android:textColor="#android:color/background_light"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/button4"
app:layout_constraintStart_toStartOf="#+id/button4"
app:layout_constraintTop_toBottomOf="#+id/button4"
app:layout_constraintVertical_bias="0.007" />
<Button
android:id="#+id/button4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="#drawable/rounded_button"
android:fontFamily="#font/pt_mono"
android:onClick="input"
android:text="#string/inp"
android:textAlignment="center"
android:textColor="#android:color/background_light"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="#+id/editText9"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="#+id/editText9"
app:layout_constraintTop_toBottomOf="#+id/editText9" />
<EditText
android:id="#+id/editText8"
android:imeOptions="normal"
android:layout_width="320dp"
android:layout_height="28dp"
android:layout_marginTop="72dp"
android:autofillHints=""
android:background="#drawable/rounded_text"
android:ems="10"
android:fontFamily="#font/pt_mono"
android:hint="#string/usrname"
android:inputType="textEmailAddress"
android:paddingLeft="10dp"
android:textAlignment="textStart"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="#+id/textView21"
app:layout_constraintHorizontal_bias="0.494"
app:layout_constraintStart_toStartOf="#+id/textView21"
app:layout_constraintTop_toBottomOf="#+id/textView21" />
<EditText
android:id="#+id/editText9"
android:layout_width="0dp"
android:layout_height="28dp"
android:layout_marginTop="8dp"
android:autofillHints=""
android:background="#drawable/rounded_text"
android:paddingLeft="10dp"
android:ems="10"
android:fontFamily="#font/pt_mono"
android:hint="#string/pass"
android:inputType="textPassword"
android:textAlignment="textStart"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="#+id/editText8"
app:layout_constraintStart_toStartOf="#+id/editText8"
app:layout_constraintTop_toBottomOf="#+id/editText8" />
<TextView
android:id="#+id/textView21"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="52dp"
android:fontFamily="#font/pt_mono"
android:text="#string/train_tem"
android:textAlignment="center"
android:textColor="#color/btext"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
The Kotlin code is as follows:
class trainingT : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.title = "Training Template"
setContentView(R.layout.activity_training_t)
//getuserkeystroke()
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
return when (keyCode) {
KeyEvent.KEYCODE_D -> {
getuserkeystroke(keyCode)
true
}
else -> super.onKeyDown(keyCode, event)
}
}
private fun getuserkeystroke(keyCode: Int){
Log.d("D should be displayed", "Is it displayed?")//keyCode.toString())
val toast = Toast.makeText(getApplicationContext(), "D is Pressed", Toast.LENGTH_LONG)
val layout = toast.getView() as LinearLayout
if (layout.childCount > 0) {
val tv = layout.getChildAt(0) as TextView
tv.gravity = Gravity.CENTER_VERTICAL or Gravity.CENTER_HORIZONTAL
}
toast.show()
}}
So far I am stuck on point number "a". I am missing something I know that, as the key pressed has to be recognized inside the Editext space, but I have no idea how to. The Kotlin code should call the getuserkeystroke() function as soon as "d key" (I was thinking of recognizing at least a single key and after that random keys) is pressed, display a debug message in the log and should show a toast but its not working.
Please suggest how should I proceed in order to recognize the keys pressed in the Android soft keyboard when typing in real time? And also some suggestions on how to acquire the data I mentioned in points "b", "c" and "d".
The activity screenshot is as follows: Screenshot
Is it possible to use data binding to bind current layout elements? For example I would like to show some text when checkbox is clicked, so I would like to have something like this:
<CheckBox
android:id="#+id/myCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="check me"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="some text"
android:visibility="#{myCheckBox.isChecked() ? View.VISIBLE : View.GONE}" />
I know how to do this from java code, I just wonder if there is a way to implement such behaviour by only modifying xml files?
Create one observable field in your ViewModel.
public class ViewModel {
public ObservableBoolean mCheckBox = new ObservableBoolean(false);
}
And modify your layout xml file:
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="#={viewModel.mCheckBox}"
android:text="check me" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="some text"
android:visibility="#{viewModel.mCheckBox ? View.VISIBLE : View.GONE}" />