I made a custom background for a button and also for different button states. But now I made to a point that I cannot understand.
When button is in normal state then it looks just fine. But when I press the button, I need to move text down few pixels because button background image moving (actually it feels like it moving on the image, because first there's border under the button and when it's in pressed state then this border disappears). Please see image below.
How can I move the buttons text in the button when buttons state is pressed? (maybe padding somehow or layout custom for a button)
The Pēteris Caune answer works worse than overriding setPressed(). But everithing OK with setPressed until you test your app at ICS or lower device and add button as listview item. To archieve this I've improved my button's class:
this might just work:
I did not try it myself but if you use nine-patch as a background drawable for both states then you should consider setting proper padding box in pressed state drawable. See details here.
You can use padding on the view. You can add an OnTouchListener to the button or view like
The ontouchlistener will let your know when the button is pressed and not.
Setting padding in 9-patch didn't work for me. Setting padding in touch listeners is messy, would litter code anywhere buttons are used.
I went with subclassing
Button
, and it turned out reasonably tidy. In my case, I wanted to offset icon (drawableLeft
) and text 1px left and 1px down.Subclassed button widget:
And use it in layout like this:
Few notes:
I did not use
StateListDrawable
for background, and am instead switching backgrounds in code. When I tried usingStateListDrawable
, there would be small pause between padding change and background change. That didn't look good.Setting background resets padding, so don't need to adjust padding in
ACTION_UP
caseIt was important to increase top and left padding, and at the same time decrease bottom and right padding. So the size of content area stays the same and content area is effectively just shifted.