【问题标题】:Initialize ImageView in companion Object Kotlin在配套对象 Kotlin 中初始化 ImageView
【发布时间】:2018-02-23 13:27:27
【问题描述】:

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

【问题讨论】:

    标签: android kotlin kotlin-companion


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,我还有一个问题,所以如果我们在伴生对象中定义 onCreate,所有其他视图都应该定义为静态的吗?
    • @vinaykumar 我们不能在同伴下定义 onCreate,也不能在 onCreate 下定义同伴。它应该是类级别的访问权限。
    • 是的,我对括号感到困惑我明白了谢谢您的帮助
    • 如果您觉得有帮助,请采纳答案,让其他人觉得有用:)
    • 是的,是的,我尝试投票,但我没有足够的声誉,再次感谢 :)
    【解决方案2】:

    如果你想在运行时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
        }
    

    【讨论】:

    • 这个 val imageView = ImageView(this) imageView.setImageResource(R.drawable.android_logo)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多