0

To support RTL even in older version of Android, I can simply do the following for TextView.

TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(
    textView, 0, 0, R.drawable.baseline_recommend_24, 0
);

But, what about Button? Is there something like ButtonCompat class?

Currently, I am getting warning from compiler, on old API, if I write the code the following way.

// button is type Button.
button.setCompoundDrawablesRelativeWithIntrinsicBounds(
    smallLockedIconResourceId, 0, 0, 0
);
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

1 Answers1

0

I tried to build my own utility class since I cannot find an official one.

public class ButtonCompat {
    public static void setCompoundDrawablesRelativeWithIntrinsicBounds(Button button, int start, int top, int end, int bottom) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            button.setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom);
        } else {
            if (isLeftToRight()) {
                button.setCompoundDrawablesWithIntrinsicBounds(start, top, end, bottom);
            } else {
                button.setCompoundDrawablesWithIntrinsicBounds(end, top, start, bottom);
            }
        }
    }

    public static Drawable[] getCompoundDrawablesRelative(@NonNull Button button) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return button.getCompoundDrawablesRelative();
        } else {
            if (isLeftToRight()) {
                return button.getCompoundDrawables();
            } else {
                // If we're on RTL, we need to invert the horizontal result like above
                final Drawable[] compounds = button.getCompoundDrawables();
                final Drawable start = compounds[2];
                final Drawable end = compounds[0];
                compounds[0] = start;
                compounds[2] = end;
                return compounds;
            }
        }
    }
}

I am using this method to determine left/ right

https://stackoverflow.com/a/26550588/72437

public static boolean isLeftToRight() {
    return MyApplication.instance().getResources().getBoolean(R.bool.is_left_to_right);
}
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875