Where'd padding go, when setting background Drawable?

后端 未结 16 1346
攒了一身酷
攒了一身酷 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:53

    Backward compatable version of cottonBallPaws's answer

    /** 
      * Sets the background for a view while preserving its current     padding. If the background drawable 
      * has its own padding, that padding will be added to the current padding. 
     *  
     * @param view View to receive the new background. 
     * @param backgroundDrawable Drawable to set as new background. 
     */ 
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @SuppressWarnings("deprecation")
    public static void setBackgroundAndKeepPadding(View view, Drawable backgroundDrawable) {
        Rect drawablePadding = new Rect();
        backgroundDrawable.getPadding(drawablePadding);
        int top = view.getPaddingTop() + drawablePadding.top;
        int left = view.getPaddingLeft() + drawablePadding.left;
        int right = view.getPaddingRight() + drawablePadding.right;
        int bottom = view.getPaddingBottom() + drawablePadding.bottom;
    
        int sdk = android.os.Build.VERSION.SDK_INT;
        if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackgroundDrawable(backgroundDrawable);
        } else {
            view.setBackground(backgroundDrawable);
        }
        view.setPadding(left, top, right, bottom);
    }
    

提交回复
热议问题