【问题标题】:how to pass imageButton and drawable file in function inside a fragment如何在片段内的函数中传递imageButton和drawable文件
【发布时间】:2020-07-04 15:33:33
【问题描述】:

是否可以将 imagebutton 和可绘制文件 ( image ) 作为片段内的函数参数传递 我已经这样做了,但它显示错误

fun def(right :Drawable , x:ImageButton){
            val bitmap=BitmapFactory.decodeResource(resources,R.drawable.right)
            val rounded=RoundedBitmapDrawableFactory.create(resources,bitmap)
            rounded.isCircular=true
            val image = root.findViewById<View>(R.id.x) as ImageButton
            image.setImageDrawable(rounded)

        }

【问题讨论】:

  • 不要使用 x.setImageDrawable 创建图像变量,因为 x 已经是 imagebutton 了?
  • x.setImageDrawable 在片段中不起作用
  • 怎么样?由于图像作品和类型相同
  • 显示错误信息
  • drawable怎么办,不识别“正确”参数

标签: android kotlin imagebutton


【解决方案1】:

正如@P.Juni 建议的那样,尝试使用imageButton.setImageDrawable

但如果你坚持将按钮和可绘制对象发送到函数中,你可以这样做。

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

    val imageButton = findViewById<ImageButton>(R.id.imageButton);
    def(R.drawable.ic_launcher_background, imageButton);
}

fun def(drawableId: Int, imageButton: ImageButton){
    val bitmap= BitmapFactory.decodeResource(resources, drawableId)
    val rounded= RoundedBitmapDrawableFactory.create(resources,bitmap)
    rounded.isCircular=true
    imageButton.setImageDrawable(rounded)
}

【讨论】:

  • 但是当我调用def函数时它无法识别drawable参数
【解决方案2】:

其实BitmapFactory.decodeResource需要resources和drawableId

root.findViewById&lt;View&gt; 也需要 layoutId

所以你可以把你的功能改成这个

fun def(drawableId: Int, layoutId: Int) {
    val bitmap=BitmapFactory.decodeResource(resources, drawableId)
    val rounded=RoundedBitmapDrawableFactory.create(resources,bitmap)
    rounded.isCircular=true
    val image = root.findViewById<View>(layoutId) as ImageButton
    image.setImageDrawable(rounded)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    相关资源
    最近更新 更多