0

Im trying to dynamically create edittext in Kotlin on button click. The Button click invokes below function. The click will also increment the count value. Getting type exception while attempting it. :

int count = 0
 fun addrow() {
        val defect: FloatingActionButton = findViewById(id)

        val gridLayout: GridLayout = findViewById(gl)
        gridLayout.visibility = View.VISIBLE
        val eqp = EditText(this)
       
        eqp.hint = "Eqp"
        eqp.textSize = 14F
        eqp.width = 200
        eqp.id = ("R.id"+count).toInt() //Error for this command

}

1 Answers1

0

Method 1:

You can setup a list of IDs that you'll use later in R.id class using an XML resource file:

1- Create the following file res/values/ids.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
        <item type="id" name="view1" />
        <item type="id" name="view2" />
        <item type="id" name="view3" />
</resources>

2- In your activity you can call

eqp.id = R.id.view1

Method 2:

Since API 17, you can use View.generateViewId():

view.setId(View.generateViewId());

For apps targeting API level 16 or lower, use ViewCompat.generateViewId() instead:

view.setId(ViewCompat.generateViewId());
Hayssam Soussi
  • 903
  • 7
  • 16