Where'd padding go, when setting background Drawable?

后端 未结 16 1300
攒了一身酷
攒了一身酷 2020-12-03 00:41

I have this issue on my EditText and Button views, where I have a nice padding for them to space away from the text, but when I change the backgrou

16条回答
  •  情深已故
    2020-12-03 00:42

    Most of answers are correct but should handle the background setting correctly.

    First get the padding of your view

    //Here my view has the same padding in all directions so I need to get just 1 padding
    int padding = myView.getPaddingTop();
    

    Then set the background

    //If your are supporting lower OS versions make sure to verify the version
    if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
        //getDrawable was deprecated so use ContextCompat                            
        myView.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.bg_accent_underlined_white));
    } else {
        myView.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_accent_underlined_white));
    }
    

    Then set the padding the view had before the background change

    myView.setPadding(padding, padding, padding, padding);
    

提交回复
热议问题