enter image description hereI just have this:
package com.example.world
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener() {
// Do some work here
}
}
}
But on this line:
button.setOnClickListener() {
// Do some work here
}
it says:
Unresolved reference: button
And I dont see the hint for important the correct library.
So what kind of library I have to import then?
Thank you
if I do it like this:
val btn_click = findViewById(R.id.button) as Button
btn_click.setOnClickListener(){
Toast.makeText(this#MainActivity, "YOu clicked on me", Toast.LENGTH_LONG).show()
}
Then it works.
But that is not necessarily I have read.
You dont have to make a referenct to the button.
So you just can do this:
button.setOnClickListener... but what is the correct library for that?
You can't use 'abstract' button, you need to find it in layout by element id (You can have many buttons in your layout, how you will find correct button without id?) If you wouldn't like to find layout elements by id, you can take a look on Android View Binding here: https://developer.android.com/topic/libraries/view-binding.
Related
I was trying to implement viewBinding in Kotlin android studio project but it pops up an error like this: Unresolved reference: inflate I tried all the suggestions given on this site and the actions suggested by android studio (to import various things), but I was still not able to resolve it. My code is as follows:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View.inflate
import androidx.core.content.res.ColorStateListInflaterCompat.inflate
import androidx.core.graphics.drawable.DrawableCompat.inflate
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityMainBinding.inflate(layoutInflater)
}
}
I have already implemented veiwbinding in buid gradle:
android {
...
buildFeatures {
viewBinding true
}
...
}
Can anyone please tell me:
what's the solution to this problem?
what exactly is causing this problem?
Try adding a button in your xml and call it in the activity file by setOnClickListener. This is to check if the layout is inflating without any issue. NOTE: add setContentView(binding.root) like I did in the onCreate
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityMainBinding.inflate(layoutInflater)
// Add this line
setContentView(binding.root)
// continueBtn --> the nameof the button id the xml
binding.continueBtn.setOnClickListener {
println("HELLO THERE")
}
}
Hi im new in android and i read that i can directly reference id from activity_main to mainAcctivity.kt without using findviewbyid.When i do that i get an error but my ids are correct:
This is the error Unresolved reference: button and Unresolved reference: textView
This is my code
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get reference to button
//val btnClickMe = findViewById(R.id.button) as Button
//val myTextView = findViewById(R.id.textView) as TextView
var timesClicked = 0
// set on-click listener
button.setOnClickListener {
timesClicked += 1
textView.text = timesClicked.toString()
Toast.makeText(this#MainActivity, "Hello Don.", Toast.LENGTH_SHORT).show()
}
}
}```
Please help out,i tried to import android.widget.button and textView that option is not available but when i hardcode the text appears inactive.
You can make use of ViewBinding to reduce the use of findViewById. You can find an example here.
You can go through this blog to have more insight on how to use ViewBinding.
For the above code, you can resolve the issue using the code below:
val myTextView = findViewById<TextView>(R.id.textView)
val btnClickMe = findViewById<Button>(R.id.button)
I've just started learning android development and Android Studio is a complete mess after xcode ;)
I have an element with ID "mybutton" and i want to use it in my kotlin code. So, to avoid using findViewById i want to use it's id (which is "mybutton"). But when i enter mybutton in the code IDE doesn't understand it and doesn't ask me to import anything.
I've just seem in online course that it should ask if i want to use "mybutton" from activity_main but in my case it does not. So i don't know how to address the elements by id ;)
Please help
package com.example.helloworld
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Button
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get reference to button
val btn_click_me = findViewById(R.id.mybutton) as Button
var myTextView = findViewById(R.id.textView) as TextView
var timesClicked = 0
// set on-click listener
mybutton.setOnClickListener { // <<------ here, mybutton is red and i can't use it
Toast.makeText(this#MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
myTextView.text = "Hey it's me again, "
timesClicked += 1
}
}
Am i doing something wrong? May be i should activate something in IDE?;)
i found that i should add the following line
import kotlinx.android.synthetic.main.content_main.*
but to add it i had to add also these 2 lines
In project-level build.gradle
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
}
}
and apply the kotlin-android-extensions plugin:
In module-level build.gradle
apply plugin: 'kotlin-android-extensions'
Is there something wrong with me? It's my first "hello world" on android.. it is normal i should invent a hyperloop to use ID-reference?
I wanted to connect a viewPager with an adapter (like this: viewPager.addOnPageChangeListener()), but the letters of the pageChangeListener just turn red like it wasn't a valid code...What am I doing wrong?? Heres a screenshot:
[1]: https://i.stack.imgur.com/IOYJY.png
Context: I'm currently working on a game with a few fragments where you can choose your game cards. I need the pageChangeListener to change the pictures of them cards. Maybe there could be another way to do this but i don't know how...
package com.suffv1
import android.os.Bundle
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager.widget.ViewPager
import com.example.suff_02.Adapter2
import com.example.suff_02.R
import com.example.suff_02.kartenmodell
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(){
private lateinit var actionbar: ActionBar
private lateinit var liste: ArrayList<kartenmodell>
private lateinit var myAdapter: Adapter2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
super.setContentView(R.layout.activity_main)
actionbar = this.supportActionBar!!
loadCards()
viewpager2.addOnPageChangeListener(object: ViewPager.OnPageChangeListener{
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
val title = liste[position].KartenImage
actionbar.title = title
}
})
}
private fun loadCards() {
liste = ArrayList()
liste.add(kartenmodell(R.drawable.bier_radler_klein_level_1))
liste.add(kartenmodell(R.drawable.bier_hopfentrunk_klein_level_1))
liste.add(kartenmodell(R.drawable.bier_butt_light_klein_level_1))
liste.add(kartenmodell(R.drawable.bier_becks_klein_level_1))
liste.add(kartenmodell(R.drawable.bier_tyskie_klein_level_1))
myAdapter = Adapter2(this, liste)
viewpager2.adapter = myAdapter
viewpager2.setPadding(100, 0, 100, 0)
}
}
Looks like you are using ViewPager2 not the original Viewpager and Viewpager2 does not have Page Change Listeners it instead has Page Change Callbacks
So you are using the wrong method to get notified when a pages is changed.
Instead do something like
var myPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
Toast.makeText(this#MainActivity, "Selected position: ${position}",
Toast.LENGTH_SHORT).show()
}
}
viewpager.registerOnPageChangeCallback(myPageChangeCallback)
Though architecturally a lot of times it is bad form to use a OnPageChangeCallback as you are likely breaking the encapsulation idea of the Fragment and it can be better to use the lifecycle state change to Resumed of the Fragment to do things when a page(Fragment) is selected. e.g. put the code in the Fragments onResume method.
Though in this case of setting the actionbar title it is probably ok architecturally to use a OnPageChangeCallback
To create a AddOnPageChangeListener(), you do it as:
//See how, you have to use object to create an Object of the interface OnPageChangeListener.
//This is how you do for other listeners/interfaces/class as well when you've to implement its member functions instead of new in java.
viewPager.addOnPageChangeListener(object: ViewPager.OnPageChangeListener{
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
TODO("Not yet implemented")
}
override fun onPageSelected(position: Int) {
TODO("Not yet implemented")
}
override fun onPageScrollStateChanged(state: Int) {
TODO("Not yet implemented")
}
})
But, further in Kotlin, you can use Kotlin functions as
//This is for onPageSelected only.
viewPager.onPageChangeListener{ position: Int ->
//This position is the selected Page's position
}
please the app keeps crashing on my phone when i try to add the values of two edit text in android studio
i've tried all i can changing the data types
package com.example.danculator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
lateinit var addbtn: Button
lateinit var fnum: EditText
lateinit var snum: EditText
lateinit var ans: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
addbtn=findViewById(R.id.add) as Button
fnum=findViewById(R.id.fnum) as EditText
snum=findViewById(R.id.snum) as EditText
ans=findViewById(R.id.ans) as EditText
addbtn.setOnClickListener {
ans.setText(fnum.text.toString().toInt() + snum.text.toString().toInt())
}
}
}
Don't use setText(int) that expects a resource id but rather use setText(CharSequence). That is, convert your Int computation to result to a String:
ans.setText((fnum.text.toString().toInt() + snum.text.toString().toInt()).toString())
Also, for future reference, examining the crash stacktrace should be the first step when trying to figure out what is wrong. See Unfortunately MyApp has stopped. How can I solve this?
I never used Kotlin before,but take a look at this part of code:
ans.setText(fnum.text.toString().toInt() + snum.text.toString().toInt())
In this part you are sum two integer values and want to set them as text for ans while you should use a string value for ans.So you should convert this to string again:
ans.setText((fnum.text.toString().toInt() + snum.text.toString().toInt()).toString())