Search code examples
androidimagebuttonnine-patch

ImageButton setBackgroundDrawable nine patch wont scale


buttons

Here are 2 screenshots, they dont have the same size because the left is from emulator the right from the device. Should have taken both from the device, sorry for this.

Both use the same drawable.

Left: background set in the layout:

        <ImageButton
        android:id="@+id/backFromOldCurves"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/backunpressed"
        android:paddingLeft="10sp"
        android:paddingRight="10sp"
        android:src="@drawable/navigationpreviousitem" />

Right: background set dynamically in onTouch on ACTION_UP:

public boolean onTouch(View v, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        v.setBackgroundDrawable(getResources().getDrawable(R.drawable.backpressed));

    }
    if (event.getAction() == MotionEvent.ACTION_UP) {
        v.setBackgroundDrawable(getResources().getDrawable(R.drawable.backunpressed));
        onClick(v);

    }

    return true;

}

Casting the Drawable to NinePatchDrawable in setBackgroundDrawable doesnt work. How could i work this around ?


Solution

  • Why you don't use

    v.setBackgroundResource(R.drawable.backpressed);
    

    ?

    Edit: Don't return true in onTouch(). Return false and you won't have to call onClick() when MotionEvent.ACTOIN_UP gets triggered.

    public boolean onTouch(final View v, final MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            v.setBackgroundResource(R.drawable.backpressed);
        case MotionEvent.ACTION_UP:
            v.setBackgroundResource(R.drawable.backunpressed);
        default:
            Thread.sleep(50); // sleep for performance, otherwise you'd get flooded with ACTION_MOVE
        }
        return false; // return false to not consume the event
    }