我正在尝试在伴随对象中初始化一个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有没有其他方法?
答案 0 :(得分:0)
建议不要使用静态视图,因为它可能会导致内存泄漏,但如果仍然需要静态视图,可以试试这个: -
companion object {
lateinit var imageView: ImageView
}
override fun onCreate(savedInstanceState: Bundle?) {
imageView =findViewById<ImageView>(R.id.imageView)
}
答案 1 :(得分:0)
如果你想在运行时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
}