mohsen
mohsen

Reputation: 1235

How to convert view object to my layout in kotlin

How to access page.questionTextView in setAnswer function

//Create the given page (indicated by position)
override fun instantiateItem(container: ViewGroup, position: Int): Any {
    val page = inflater.inflate(R.layout.layout_question, null)
    page.questionTextView.text = "hi"

    //Add the page to the front of the queue
    (container as ViewPager).addView(page, 0)
    return page
}

private fun setAnswer(page: View){
    //how to access page.questionTextView
}

Upvotes: 1

Views: 787

Answers (3)

mohsen
mohsen

Reputation: 1235

I found the solution: i use "with" method to access to page.questionTextView

private fun setAnswer(page: View){
    with(page){
        questionTextView.text = "hi"
    }
}

Upvotes: 1

David Jarvis
David Jarvis

Reputation: 2809

If you create the page var global to your class you can initialize it within your instantiateItem function and use it to access your view from the setAnswer function.

Try this

private lateinit var page: View
//Create the given page (indicated by position)
override fun instantiateItem(container: ViewGroup, position: Int): Any {
    page = inflater.inflate(R.layout.layout_question, null)
    page.questionTextView.text = "hi"

    //Add the page to the front of the queue
    (container as ViewPager).addView(page, 0)
    return page
}

private fun setAnswer(){
    //how to access page.questionTextView
    page.questionTextView.text = "your answer"
}

Upvotes: 0

matwr
matwr

Reputation: 1571

You can declare the page variable at the top level i.e. directly inside the package. By default, if you do not specify a visibility modifier, your variable will be public. This means that it will be accessible everywhere (within the package).

More info about visibility in kotlin : https://kotlinlang.org/docs/reference/visibility-modifiers.html

Upvotes: 0

Related Questions