2

I have a XML file and I want to use a text view from inside that, to the best of my knowledge, view binding can be used to access views from id using:

binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.<textview_id_name>.text = "Some Text"

But I wish to access a view in another class which does not extend AppCompatActivity class.

My MainActivity

class MainActivity : AppCompatActivity() {
    companion object CompanionObject{
        lateinit var binding:ActivityMainBinding
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.recyclerView.layoutManager = LinearLayoutManager(this);
    }
}

Class from which I want to access textview named 'titleView', I want to have something like this.

titleView.text = "Some Message"
2
  • 2
    But I wish to access a view in another class which does not extend AppCompatActivity class. this is most likely a bad idea, regardless of using viewbinding, what's the point of doing that ? Commented Feb 26, 2022 at 23:21
  • 2
    Do not put a binding reference in a companion object! This will leak your views. Commented Feb 27, 2022 at 0:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.