I have ImageButtons
and i send a Toast from override fun onCreate(savedInstanceState: Bundle?)
when its clicked successful.
I want loop trough all ImageButtons to add the setOnClickListener to them.
this works:
works without a loop:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<ImageButton>(R.id.r1col1).setOnClickListener {
toastContentDescription(it)
}
}
private fun toastContentDescription(it: View) {
val contentDescription = it.contentDescription
val myToast = Toast.makeText(applicationContext, contentDescription, Toast.LENGTH_SHORT)
myToast.show()
}
}
works not, not start anymore
I found a example for Android Java Buttons here: How to get all Buttons ID's in one time on Android
So i modified my code to following. But then the app not start anymore (gives me no errors).
i guess i have to get the id first and then the problem is solved.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
for (i in 0..4) {
val id: Int = resources.getIdentifier("R.id.r1col$i", "id", this.packageName)
findViewById<ImageButton>(id).setOnClickListener {
toastContentDescription(it)
}
}
}
private fun toastContentDescription(it: View) {
val contentDescription = it.contentDescription
val myToast = Toast.makeText(applicationContext, contentDescription, Toast.LENGTH_SHORT)
myToast.show()
}
}
Is there any way to set the setOnClickListener to all ImageButtons in a loop (etc.) Code?
Remove the "R.id." prefix from the string you’re passing.
Related
I've tried making the below method for a button on Android Studio, and when I run, the app crashes.
MainActivity : AppCompatActivity() {
val button = findViewById(R.id.button) as Button
var count = 0
val textView = findViewById(R.id.textView) as TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener{
buttonAction()
}
}
fun buttonAction(){
count = count+1
textView.text = count.toString()
}
}
I am well aware that in order for the button to work, you need to put stuff into the "button.setOnClickListener" part (see below). However, I want to make sure that my code is as neat and clean as possible by calling the method inside the "button.setOnClickListener" rather than put every stuff into that part.
MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById(R.id.button) as Button
var count = 0
val textView = findViewById(R.id.textView) as TextView
button.setOnClickListener{
count = count+1
textView.text = count.toString()
}
}
}
Is there any fixes for the 1st code, or would I have to settle for the 2nd code?
class MainActivity : AppCompatActivity() {
private var count = 0
private var button: Button? = null
private var textView: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.button)
textView = findViewById(R.id.textView)
button?.setOnClickListener {
buttonAction()
}
}
private fun buttonAction() {
count += 1
textView?.text = count.toString()
}
}
The reason for your app crash is that you're trying to assign views(button and textView) that do not (yet) exist by calling them before onCreate.
val button = findViewById(R.id.button) as Button
val textView = findViewById(R.id.textView) as TextView
override fun onCreate(savedInstanceState: Bundle?) { ...
Just put this lines inside onCreate after setContentView(R.layout.activity_main).
You can think of it as trying to shake your friend's hand before meeting him.
And about making code clean, I wouldn't worry about it too much, your second solution is good enough for a beginner.
Not sure if you're aware of Android Basics in Kotlin course, but it can help you a lot if you follow it step by step.
And just to give you an answer, here is a code
class MainActivity : AppCompatActivity() {
var count = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById(R.id.button) as Button
val textView = findViewById(R.id.textView) as TextView
button.setOnClickListener{
buttonAction()
textView.text = count.toString()
}
}
fun buttonAction(){
count += 1
}
}
It's not the smoothest solution, but as i said, it's good enough
The first time I tap the button, both the image1 and text1 changed to image2 & text2. How do I change both the image and text back to 1st set the 2nd time I tap the button and change them to 2nd set the 3rd time I tap the button ?
Here is my current codes:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun eating(view: View?) {
val afterEatingText:String="I am so full!!"
displayMessage(afterEatingText)
displayImage(R.drawable.after_cookie)
}
private fun displayMessage(message: String) {
val afterEatingText = findViewById<View>(R.id.before_eating) as TextView
afterEatingText.text = message
}
private fun displayImage(imagesource: Int){
val afterEatingImage: ImageView = findViewById<View>(R.id.before_cookie) as ImageView
afterEatingImage.setImageResource(imagesource)
}
}
var isClick:Boolean=false
var afterEatingText :TextView?=null
var afterEatingImage:ImageView?=null
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
afterEatingImage= findViewById<ImageView>(R.id.before_cookie) // find your id you can also direct call with its ids in kotlin
afterEatingText = findViewById<ImageView>(R.id.before_eating)
}
fun eating(view: View?) {
if(isClick){
isClick=true
// set your first image and text
}else {
isClick=false
val afterEatingText:String="I am so full!!"
displayMessage(afterEatingText)
displayImage(R.drawable.after_cookie)
}}
private fun displayMessage(message: String) {
afterEatingText.text = message
}
private fun displayImage(imagesource: Int){
afterEatingImage.setImageResource(imagesource)
}
}
what to do so?
I declared the val here, so that i can use the val e11 in all the function but it get crashes and why?
//val e11=findViewById<EditText>(R.id.e1)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_lifecycle)
val b11=findViewById<Button>(R.id.b1)
b11.setOnClickListener{
startActivity(Intent(this,another::class.java))
}}
override fun onStart() {
super.onStart()
Toast.makeText(this, "am started", Toast.LENGTH_SHORT).show()
}override fun onResume() {
super.onResume()
Toast.makeText(this, "am resumed", Toast.LENGTH_SHORT).show()
}
override fun onPause() {
super.onPause()
val e1=findViewById<EditText>(R.id.e1)
e1.setText("")
}
}```
Try this
private val e11 : EditText by lazy { findViewById<EditText>(R.id.e1) }
As #Kishan Maurya stated out in the comments, you are trying to find a view before the view gets created in your onCreate function. A solution could be to declare e11 globally and initiate it in your onCreate like it is most common. Or you try out #Kishan Maurya's answer.
lateinit var e11 : EditText // declare var e11 globally
// lateint is a keyword to tell that this var will be initialized later
// you need a var instead of val, because e11 should not be final
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
e11 = findViewById<EditText>(R.id.e11)
// you could also initialize like below; is simple and has better readability
// e11 = findViewById(R.id.e11) as EditText
}
I want to expand and collapse a CollapsingToolBar in android studio
when i click a button.
I want it collapsed by dafault. Im doing something wrong and i dont know what, thanks for the help.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//maybe this doesnt go here, im trying to make it collapse by default
var start = appbar.setExpanded(false)
button.setOnClickListener {
if(start == appbar.setExpanded(false)){
start = appbar.setExpanded(true)
}else{
start = appbar.setExpanded(false)
}
}
}
Try this:
class MainActivity : AppCompatActivity() {
private var isAppbarExpanded = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
if(!isAppbarExpanded){
appbar.setExpanded(true)
isAppbarExpanded = true
}else{
appbar.setExpanded(false)
isAppbarExpanded = false
}
}
}
How to convert a string to EditText , i make a EditText in one activity and then make a second activity and i get this edittext through the intent in the string then
how to assign it to the second activity's edittext , but i don't find it how to assign string to edittext.Here i used a go function that is used when onclick event is occured of button
This is my first activity
class MainActivity : AppCompatActivity() , View.OnClickListener{
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun go(v:View){
val intent=Intent(this#MainActivity,Main2Activity::class.java)
var aa=EditText1.text
intent.putExtra("name",aa)
startActivity(intent)
}
}
This is my second activity
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
var str=intent.getStringExtra("name").toString()
et21.setText(str)
}
}
In your first activity change go function as below,
fun go(v:View){
val intent=Intent(this#MainActivity,Main2Activity::class.java)
var aa=EditText1.text.toString()
intent.putExtra("name",aa)
startActivity(intent)
}
In your second activity change the last line of onCreate as below, you need to unwrap the value from an nullable type. Which can be done using let block over nullable type. Also I am assuming et21 is reference to the edit text and is properly initialised.
This solution is null safe
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
intent.getStringExtra("name")?.let {
et21.setText(it)
}
}
Its because you was trying to set charSequence to your EditText , just convert to String while getting value from FirstEditText.
inside your Second Activity -
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
intent.getStringExtra("name")?.let {
et21.setText(it)
}
}
}
Inside your first activity
fun go(v:View){
val intent=Intent(this#MainActivity,Main2Activity::class.java)
var aa=EditText1.text.toString()
intent.putExtra("name",aa)
startActivity(intent)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
val extras:Bundle =intent.extras
val nn=extras.getString("name")
eT21.setText("${nn}")
}
Or
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
eT21.setText(intent.getStringExtra("name"))
}