Android Code Snippet CreateStateListDrawableView with a Bitmap and Pressed Color

Subname: CreateStateListDrawableView

Description: This is a great sub to make custom buttons (especially pictures). You only need to set one bitmap, and this sub will create the pressed state automatically with a highlighted color to show the pressed state.

Requirements: This requires the view(cmd) be already added to an activity/panel.

B4X:
Sub CreateStateListDrawable(bmp As Bitmap,cmd As View )
    Dim C As Canvas
    Dim r1 As Rect
    Dim r2 As Rect
    Dim sld As StateListDrawable
    Dim Padding As Int
    Padding = 0
    'Create a temporary button and draw on it
    C.Initialize(cmd)
    r1.Initialize(0,0,cmd.Width,cmd.Height)
    r2.Initialize(Padding,Padding,cmd.Width-Padding,cmd.height-Padding)
    sld.Initialize
 
    C.DrawColor(Colors.RGB(58, 162, 203))
    C.DrawBitmap(bmp,Null,r2)
    cmd.Invalidate
    sld.AddState(sld.State_Pressed,cmd.Background)
 
 
    Dim bmd As BitmapDrawable
    bmd.Initialize(bmp)
    sld.AddState(sld.State_Enabled, bmd)

    cmd.Background = sld


End Sub

Tags: UI, StateListDrawable, Button, Highlight
 
Last edited:

bluedude

Well-Known Member
Licensed User
Longtime User
Interesting, can this be adapted to just show a small icon on the left side of the button? Don't want to work with nine patch right now because then I need to design custom buttons.
 

thedesolatesoul

Expert
Licensed User
Longtime User

bluedude

Well-Known Member
Licensed User
Longtime User
Actually not too bad, however it moves my button text slightly to the right. See screenshot. setCompoundDrawablesWithIntrinsicBounds works but need to get the text in the middle of the button again.
 

Attachments

  • button.png
    button.png
    24.3 KB · Views: 647

asales

Expert
Licensed User
Longtime User
I tried to put a small image on the left side of EditText (see an image sample), with the code below, but don't work:

B4X:
Sub EditTextSearch(EditTxt As EditText)
    Dim ETxt As JavaObject = EditTxt
   
    Dim img As Bitmap
    img = LoadBitmap(File.DirAssets, "search-24.png") 
   
    ETxt.RunMethod("setCompoundDrawablesWithIntrinsicBounds",Array As Object(img,Null,Null,Null))
End Sub
I get the exception:
java.lang.RuntimeException: Method: setCompoundDrawablesWithIntrinsicBounds not matched.

What am I doing wrong?

edit_btn_search.jpg
 
Top