首页 > 解决方案 > 如何更改仅满足条件的文本视图的颜色?

问题描述

好吧,基本上我有一个列表,我想要的是对于满足条件的文本视图,它们的颜色会有所不同。

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"));
}

在这种方法中,我遍历所有文本视图并尝试更改它们的颜色。这没用。

标签: javaandroidtextview

解决方案


您可以重写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;
    }

推荐阅读