2 回答
TA贡献1887条经验 获得超5个赞
我认为你有两个选择。
创建自定义 Utils.java 类
您可以创建一个自定义静态类来为您更新文本视图。
public class Utils {
public static void setText(TextView textView, BigDecimal bigDecimal) {
if(textView != null && bigDecimal != null) {
// Get context
Context context = textView.getContext();
// Set text
textView.setText(bigDecimal.toString());
// Set color
if (bigDecimal.compareTo(BigDecimal.ZERO) == -1) {
textView.setBackgroundTintList(new ColorStateListStud().getList(ContextCompat.getColor(context, R.color.lightred)));
} else if (bigDecimal.compareTo(BigDecimal.ZERO) == 1) {
textView.setBackgroundTintList(new ColorStateListStud().getList(ContextCompat.getColor(context, R.color.lightgreen)));
} else {
textView.setBackgroundTintList(new ColorStateListStud().getList(ContextCompat.getColor(context, R.color.transparent)));
}
} else {
Log.e("ERROR", "Error: TextView and/or BigDecimal is null");
}
}
然后,你可以调用:
Utils.setText(mTextView, mBigDecimal);
创建您自己的自定义 TextView
public class CustomTextView extends TextView {
public CustomTextView(final Context context) {
this(context, null);
}
public CustomTextView(final Context context,
@Nullable final AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomTextView(final Context context, @Nullable final AttributeSet attrs,
final int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setText(BigDecimal bigDecimal) {
setText(bigDecimal.toString());
// Set color
if (bigDecimal.compareTo(BigDecimal.ZERO) == -1) {
setBackgroundTintList(new ColorStateListStud().getList(ContextCompat.getColor(getContext(), R.color.lightred)));
} else if (bigDecimal.compareTo(BigDecimal.ZERO) == 1) {
setBackgroundTintList(new ColorStateListStud().getList(ContextCompat.getColor(getContext(), R.color.lightgreen)));
} else {
setBackgroundTintList(new ColorStateListStud().getList(ContextCompat.getColor(getContext(), R.color.transparent)));
}
}
}
然后,在java端:
CustomTextView mTextView = (CustomTextView) findViewById(R.id.text_view);
mTextView.setText(mBigDecimal);
在你的layout.xml中:
<com.test.CustomTextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
TA贡献1852条经验 获得超7个赞
尝试setText()在最后打电话
if (mBigDecimal.compareTo(BigDecimal.ZERO) == -1) {
payment.setBackgroundTintList(new ColorStateListStud().getList(ContextCompat.getColor(super.getContext(), R.color.lightred)));
} else if (mBigDecimal.compareTo(BigDecimal.ZERO) == 1) {
payment.setBackgroundTintList(new ColorStateListStud().getList(ContextCompat.getColor(super.getContext(), R.color.lightgreen)));
} else {
payment.setBackgroundTintList(new ColorStateListStud().getList(ContextCompat.getColor(super.getContext(), R.color.transparent)));
}
// Only then, call setText() here
payment.setText(BigDecimal.toString());
添加回答
举报