android widgetProvider : set backgroundDrawable for button

53 views Asked by At

I am trying to set background for button (a homeScreen Widget) through a configuration activity. background color is accepted from user (from a JSON) using that color, 2 GradientDrawables are prepared and added in StateListDrawable. I want to set this as background for button. but for RemoteViews there is no method that supports Drawable class and if i convert drawable to BitMap there is no method in Button that accepts BitMap for background.

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)
}

Is there a way to solve this? (I don't want to set background from resource because I won't be able to change colors)

1

There are 1 answers

1
pwnd On

If you want a bitmap as background you should use ImageButton instead. Also you dont have to use a button at all. You could use a TextView or whatever you need to display your content and gradient and then add a listener to it.