0

I am very new to Android development and actually stuck with code in tutorial for Kotlin programming for android. The code below is not working and I have tried to find alternative but no luck. Will appreciate if somebody can help we with the alternative code below is a code:

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
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)

        addSomeViews(count = 5)
    }

    fun addSomeViews(count: Int) {
        for (i in 1..count) {
            val textView = TextView(this)
            textView.text = "Hey, learner # $i"
            textView.textSize = 20f
            my_layout.addView(textView)
        }

        val button = Button(this)
        button.text = "Click me!"
        my_layout.addView(button)
    }
}  
Syed
  • 1
  • Does this answer your question? [Android - Dynamically Add Views into View](https://stackoverflow.com/questions/6216547/android-dynamically-add-views-into-view) – Morrison Chang Mar 26 '22 at 18:45
  • Unable to adopt this code. I have create liner layout. It is now not recognizing activity main. – Syed Mar 26 '22 at 19:26

1 Answers1

0

That kotlinx.synthetic stuff is deprecated - it doesn't work anymore. Instead of just referencing my_layout directly (the synthetics are supposed to look it up for you and create that variable) you need to find it yourself:

fun addSomeViews(count: Int) {
    // lookup the layout viewgroup and create a variable for it
    val my_layout = findViewById<ViewGroup>(R.layout.my_layout)
        for (i in 1..count) {
            val textView = TextView(this)
            textView.text = "Hey, learner # $i"
            textView.textSize = 20f
            // now this variable exists
            my_layout.addView(textView)
        }
    }

Aside from that... this isn't how a beginner should be learning Android imo. Creating views like this is kind of an advanced thing, mostly you never have to do it, and if you do there's a bunch of configuration you need to do on the views to make them display correctly (like the appropriate LayoutParams)

You can do it, but mostly you create your layouts in XML using the layout editor. And Compose is the new thing for writing UI in code, which is probably worth learning. It's up to you obviously, I just wanted to warn you that it's a strange thing for a beginner to be learning, and you might be better trying the Codelabs stuff instead

cactustictacs
  • 17,935
  • 2
  • 14
  • 25