I have a custom view where I have to change the background shape's color from the code based on the input.
The shape:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size
android:width="64dp"
android:height="64dp" />
<solid
android:color="#BBBBBB" />
</shape>
The custom view:
public class MyCustomView extends TextView {
public MyCustomView(Context context) {
super(context);
}
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyCustomView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void setCustomValue(long customValue) {
this.setBackgroundResource(R.drawable.shape_background);
this.setTextColor(getColor(R.color.colorCustomViewText));
this.setGravity(Gravity.CENTER);
this.setText(String.valueOf(customValue));
}
public long getCustomValue() {
return Long.parseLong(this.getText().toString());
}
private int getColor(int colorId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getContext().getColor(colorId);
} else {
return getContext().getResources().getColor(colorId);
}
}
}
The color of the shape always #BBBBBB
. I cannot change it to e.g. red
no matter which color related attribute I try. I have to change the color based on the input.