如何解决如何仅更改符合条件的文本视图的颜色?
基本上,我有一个列表,我想要的是对于符合条件的文本视图,其颜色会有所不同。
public class CustomTempAdapter extends ArrayAdapter<String> {
private Context mContext;
private int id;
private List<String> items;
public CustomTempAdapter(Context context,int textViewResourceId,List<String> list) {
super(context,textViewResourceId,list);
mContext = context;
id = textViewResourceId;
items = list;
}
@Override
public View getView(int position,View v,ViewGroup parent) {
View mView = v;
if (mView == null) {
LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(id,null);
}
TextView text = (TextView) mView.findViewById(R.id.tempView);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
items.forEach(item -> {
if (Double.parseDouble(item) > 100.00) {
text.setBackgroundColor(Color.RED);
int color = Color.argb(200,255,64,64);
text.setBackgroundColor(color);
}
});
}
return mView;
}
}
CustomTempAdapter adapter = new CustomTempAdapter(this,R.layout.customTextView,normalStrings);
ListView list = findViewById(R.id.customListView);
list.setAdapter(adapter);
当前,这仅显示空白文本视图。我尝试了另一种方法。这次使用普通的ArrayAdapter<String>
,然后每添加一个项目:
View v;
for (int i = 0; i < list.getChildCount(); i++) {
v = list.getChildAt(i);
TextView tv = v.findViewById(R.id.tempView);
if (tv != null && Double.parseDouble(tv.getText().toString()) > 100)
tv.setTextColor(Color.parseColor("#FF0000"));
}
以这种方式,我遍历所有文本视图并尝试更改其颜色。它不起作用。
解决方法
您可以按以下方式重写getView
方法:
public View getView(int position,View v,ViewGroup parent) {
View mView = v;
if (mView == null) {
LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(id,null);
}
TextView text = (TextView) mView.findViewById(R.id.tempView);
Double value = Double.parseDouble(items.get(position));
if (value > 100.00) {
int color = Color.argb(200,255,64,64);
text.setBackgroundColor(color);
} else {
text.setBackgroundColor(Color.GREEN);
}
return mView;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。