0
votes

I am trying to initialize an ImageView in companion object as I want the methods to be static but I have an error is there an alternative approach below is my code

companion object {
    lateinit var bufferingAnimation : LoadingAnimation
    var bufferingIndicator = findViewById(R.id.loading)
    fun startBufferingAnimation() {
        bufferingAnimation = LoadingAnimation(bufferingIndicator)
        bufferingAnimation.startAnimation()
    }

    fun stopBufferingAnimation() {
        bufferingAnimation.clearAnimation()
    }

}

I am not able to initialize bufferingIndicator is there any alternate approach?

2

2 Answers

1
votes

Making a static view is not recommended because it can cause memory leaks but if still you need static view, you can try this:-

companion object {
        lateinit var imageView: ImageView
    }

 override fun onCreate(savedInstanceState: Bundle?) {
        imageView  =findViewById<ImageView>(R.id.imageView)
    }
1
votes

If you want to initialise image view in runtime :-

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_image_view_example)
        val constraintLayout = findViewById(R.id.constraintLayout) as ConstraintLayout
        val imageView = ImageView(this)
        imageView.setImageResource(R.drawable.android_logo)
        constraintLayout.addView(imageView)
    }

If you having image view in xml :-

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get reference to ImageView
        val imageView = findViewById(R.id.iv_click_me) as ImageView
    }