How to change the color of only textviews that meet a condition?

Well basically I have a list and what I want is that for textviews that meet a condition, their color would be different.

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

Currently this is only displaying blank textviews. I tried a different approach. This time using a normal ArrayAdapter<String>, then whenever an item is added:

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

In this approach, I iterate through all the textviews and try to change their color. It does not work.

Answer

You could rewrite getView method as following:

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

Leave a Reply

Your email address will not be published. Required fields are marked *