在伴侣对象kotlin中初始化imageView



我试图在伴随对象中初始化一个imageView,因为我希望方法是静态的,但是我有一个错误,下面是否有其他方法是我的代码

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

我无法初始化BufferingIndicator,是否有其他方法?

不建议进行静态视图,因为它可能会导致内存泄漏,但是如果仍然需要静态视图,则可以尝试以下操作: -

companion object {
        lateinit var imageView: ImageView
    }
 override fun onCreate(savedInstanceState: Bundle?) {
        imageView  =findViewById<ImageView>(R.id.imageView)
    }

如果要在运行时 initialise image view: -

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)
    }

如果您在XML中有image view: -

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
    }

相关内容

  • 没有找到相关文章

最新更新