How to get views by ID that created programmatically?

Viewed 36

The view is created dynamically in the code:

    val textView = TextView(context).apply {
        setTextColor(Color.BLACK)
        setPadding(5,20,5,0)
        text = label
        id = lblID
    }
    
    linearLayout.addView(textView)
    

At some point, I need to get this view by ID in my fragment.

In fragment I use binding to access static views defined in XML:

private var _binding: FragmentDataBinding? = null
private val binding get() = _binding!!  

But, I do not know how to access dynamically created views by id.

How can I access programmatically the views that are created dynamically as in the example above by ID?

1 Answers

To set id for a view in code, to maintain the id's as if it would be if we do in xml, first create a new file called ids.xml- res -> values -> ids.xml with below content, you can have multiple id here if you want

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

Now you can do:

val textView = TextView(context).apply {
    setTextColor(Color.BLACK)
    setPadding(5,20,5,0)
    text = label
    id = R.id.myTextView
}
linearLayout.addView(textView)

To access the view you can just use the same id again:

val tv = linearLayout.findViewById<TextView>(R.id.myTextView)
Related