'Is there any TextViewCompat equivalent for Button class?
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
);
Solution 1:[1]
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cheok Yan Cheng |
