Search code examples
androidkotlinanko

How to get reference of custom ids in values/ids.xml


I'm using anko in recyclerView adapter for creating viewholder's view. I have done this successfully but don't know how to refer it using kotlin synthetic by view id (I want to get it without findViewById)

value/ids.xml

<resources>
<item name="txv1" type="id"/>
<item name="txv2" type="id"/>

My Anko getView Codes:

private fun getView(context: Context): View{
        return with(context){
            linearLayout {
                lparams(width = matchParent, height = wrapContent)
                padding = dip(10)
                orientation = android.widget.LinearLayout.HORIZONTAL

                //Task Number
                textView {
                    id = R.id.txv1
                    text = "TextView 22"
                    textSize = 16f
                    typeface = Typeface.MONOSPACE
                    padding =dip(5)
                }.lparams(){
                    weight = 1f
                }

                //Task Name
                textView {
                    id = R.id.txv2
                    text= "TextView 33"
                    textSize = 16f
                    typeface = android.graphics.Typeface.DEFAULT_BOLD
                    padding =dip(5)
                }
            }
        }
    }

I'm assigning custom ids from ids.xml but how to get it without findViewById

Thanks


Solution

  • After researching a lot I came to conclusion that direct reference by id of anko created views are not possible right now.
    The workaround is to use -

    val txv1 = findViewById(R.id.txv1) as TextView
    

    OR
    Declare a variable to hold reference of view created inside anko method.
    Code is given below -

        var txv1: TextView? = null
    
        private fun getView(context: Context): View{
            return with(context){
                linearLayout {        
                    txv1 = textView {
                        text = "TextView"
                    }
                }
            }
        }
    

    Hope this will help others. Thanks