2 回答

TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
我認(rèn)為你有兩個(gè)選擇。
創(chuàng)建自定義 Utils.java 類
您可以創(chuàng)建一個(gè)自定義靜態(tài)類來為您更新文本視圖。
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");
}
}
然后,你可以調(diào)用:
Utils.setText(mTextView, mBigDecimal);
創(chuàng)建您自己的自定義 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貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超7個(gè)贊
嘗試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());
添加回答
舉報(bào)