0

我正在尝试通过配置活动为按钮(homeScreen Widget )设置背景。用户(来自 JSON)使用该颜色接受背景颜色,准备 2 个 GradientDrawables 并将其添加到 StateListDrawable 中。我想将此设置为按钮的背景。但是对于 RemoteViews,没有支持 Drawable 类的方法,如果我将 drawable 转换为 BitMap,则 Button 中没有接受 BitMap 作为背景的方法。

fun configueWidget(){
    val gd = GradientDrawable()
    val gdPressed = GradientDrawable()
    val stateDrawable = StateListDrawable()
    setButtonDrawableColor(gd,gdPressed,jsonObj.getInt("color"))
    stateDrawable.addState(intArrayOf(android.R.attr.state_pressed),gdPressed)
    stateDrawable.addState(intArrayOf(),gd)
    RemoteViews(context.packageName, R.layout.widget_layout).also { views->
        views.setTextViewCompoundDrawables(R.id.widget_button,jsonObj.getInt("icon_res_id"),0,0,0)

        //i want to set button background here

        val intent = Intent(context,ButtonWidgetProvider::class.java)
        intent.action = ButtonWidgetProvider.BUTTON_CLICK
        intent.putExtra("WidgetID",widgetId)
        val pendingIntent = PendingIntent.getActivity(context, widgetId, intent, 0)
        views.setOnClickPendingIntent(R.id.widget_button,pendingIntent)
        AppWidgetManager.getInstance(context).updateAppWidget(widgetId, views)
    }
}

fun setButtonDrawableColor(drawableNormal:GradientDrawable, drawablePressed:GradientDrawable, colorInt:Int){
    val red = Color.red(colorInt)
    val green = Color.green(colorInt)
    val blue = Color.blue(colorInt)
    val newColorInt = Color.argb(0xFF,
        when{red>0x80->red-0x30;else -> red+0x30},
        when{green>0x80->green-0x30;else -> green+0x30},
        when{blue>0x80->blue-0x30;else -> blue+0x30})
    drawableNormal.colors = intArrayOf(colorInt,newColorInt)
    drawableNormal.setStroke(8,newColorInt)

    val pressedColorInt = Color.argb(0xFF,
        when{red>0x80->red-0x20;else -> red+0x20},
        when{green>0x80->green-0x20;else -> green+0x20},
        when{blue>0x80->blue-0x20;else -> blue+0x20})
    val pressedColorGradientInt = Color.argb(0xFF,
        when{red>0x80->red-0x50;else -> red+0x50},
        when{green>0x80->green-0x50;else -> green+0x50},
        when{blue>0x80->blue-0x50;else -> blue+0x50})
    drawablePressed.colors = intArrayOf(pressedColorInt,pressedColorGradientInt)
    drawablePressed.setStroke(8,pressedColorGradientInt)
}

有没有办法解决这个问题?(我不想从资源中设置背景,因为我无法更改颜色)

4

1 回答 1

0

如果你想要一个位图作为背景,你应该使用 ImageButton。此外,您根本不必使用按钮。你可以使用 TextView 或任何你需要的东西来显示你的内容和渐变,然后给它添加一个监听器。

于 2019-12-25T15:07:23.490 回答