【问题标题】:CursorAdapter strange behaviourCursorAdapter 奇怪的行为
【发布时间】:2012-04-03 15:36:57
【问题描述】:

在我的应用中,我会显示一些信息,并根据值更改 textView 的颜色。

public class DealsAdapter extends CursorAdapter {
    private Cursor mCursor;
    private Context mContext;
    private final LayoutInflater mInflater;

    public DealsAdapter(Context context, Cursor cursor) {
        super(context, cursor, true);
        mInflater = LayoutInflater.from(context);
        mContext = context;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        final View view = mInflater.inflate(R.layout.deals_row, parent, false);
        return view;
    }

    @Override
    public void bindView(View row, Context context, Cursor cursor) {
         Text View percent = (TextView) row.findViewById(R.id.tvPercent);
          percent.setText(cursor.getString(cursor
                .getColumnIndex(DBHelper.D_PERCENT)));
          float percentV = cursor.getFloat(cursor
                .getColumnIndex(DBHelper.D_PERCENT));
          if (percentV >= 41 && percentV <= 70) {
            // Orange
            percent.setTextColor(Color.parseColor("#F58549"));
        } else if (percentV >= 71) {
            // Green
            percent.setTextColor(Color.parseColor("#17D11D"));
        }
}

问题是在我上下滚动后颜色开始混合但值保持不变。

有什么建议吗?

编辑:在 xml 中,我将颜色设置为红色,仅在需要时更改。

【问题讨论】:

    标签: java android listview cursor android-cursoradapter


    【解决方案1】:

    如果percentV &lt; 41,您没有明确设置颜色。这意味着该项目将保留该视图之前的任何颜色,从而产生不可预测的结果。

    这是因为出于性能原因,每个项目的 View 可能会被重复使用。如果您从屏幕顶部滚动一个项目,则相同的View 可能会用于出现在屏幕底部的新项目,以节省每次膨胀一个新项目的成本。您必须在bindView() 中明确设置默认颜色,否则View 将保留它包含的最后一个项目的任何颜色。

    【讨论】:

    • 我将 xml 中的颜色设置为红色,仅在需要时更改。
    • 你不能那样做。 ListView 中的视图被重用。如果您滚动屏幕顶部的一项,出于性能原因,屏幕底部出现的新项目将使用相同的视图。您必须在bindView() 中明确设置默认颜色。
    • 哦,我忘了视图被重用了,它现在可以工作了。谢谢。
    【解决方案2】:

    你必须检查 percentV 是否小于 41。

    if (percentV >= 41 && percentV <= 70) {
      // Orange
      percent.setTextColor(Color.parseColor("#F58549"));
    } else if (percentV >= 71) {
      // Green
      percent.setTextColor(Color.parseColor("#17D11D"));
    } else {
      // DEFAULT color (if percentV < 41)
      percent.setTextColor(DEFAULT COLOR);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 2015-07-20
      • 2010-10-03
      • 2021-07-12
      • 2013-10-04
      • 2019-01-23
      相关资源
      最近更新 更多