java - 如何更改仅满足条件的文本视图的颜色?
问题描述
好吧,基本上我有一个列表,我想要的是对于满足条件的文本视图,它们的颜色会有所不同。
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);
目前这仅显示空白文本视图。我尝试了不同的方法。这次使用 normal 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;
}
推荐阅读
- terraform - Terraform 目录结构
- reactjs - 什么是类在 React 中扩展 React.component
- manim - Manim 'coords_to_point' 新版本
- python - 使用 pysimplegui 在行中使用按钮更新窗口布局
- python - 检查动态网站上的文件是否已更改
- python - pandas 列中子类别的中位数
- onesignal - 在 Firebase 实时数据库中更新时删除密钥
- java - Java final 静态字段在第一次使用时为空
- python - 在python中将数据填充到给定的指针(cpp指针)
- javascript - 使用javascript获取元素中的最后一个标签