Set padding to your custom views

When you are developing an Android app and trying to implement your own custom view which extends TextView for the first time, there is something you should be careful.

When you try to add padding to your custom TextView (I do not know maybe you want some kind of view with text inside rounded-shape bordered background) and also background, you need to make sure to set background before set padding.

Below is the sample of my custom text view code and you will notice inside the init() method I call setPadding but the padding were not set correctly this way.

public class CustomTextView extends TextView {
  public TagTextView(Context context) {
    super(context);
    init();
  }

  public CustomTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
  }

  public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
  }

  @TargetApi(LOLLIPOP)
  public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init();
  }

  private void init() {
    // some configurations like set clickable, layout params, etc.
    ...
    setPadding(left, top, right, bottom);
    setBackground(ContextCompat.getDrawable(getContext(), R.drawable.some_background));
  }

The truth is when I tried calling setBackground before setting padding it just worked fine, like so:

  setBackground(ContextCompat.getDrawable(getContext(), R.drawable.some_background));
  setPadding(left, top, right, bottom);

In my case it was custom TextView but maybe it is the same for other custom views. (like LinearLayout, RelativeLayout, etc.)

I apologize for not investigating further more to figure out the real reason why and why not padding is set properly if there is no background. I just wanted to leave a tiny rough note here. If you are familiar with this issue and you know more details about this it would be helpful for me if you could leave a comment here.