0

我正在尝试在伴随对象中初始化 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 是否有任何替代方法?

4

2 回答 2

1

如果你想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)
    }

如果你有image viewxml : -

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
    }
于 2018-02-23T05:27:27.427 回答
1

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

companion object {
        lateinit var imageView: ImageView
    }

 override fun onCreate(savedInstanceState: Bundle?) {
        imageView  =findViewById<ImageView>(R.id.imageView)
    }
于 2018-02-23T05:10:35.353 回答