【问题标题】:Wrong backgroundcolor on ListView inflateListView inflate 上的背景颜色错误
【发布时间】:2014-11-19 12:50:25
【问题描述】:

所以我有一个使用自定义适配器的ListView。我希望项目的背景颜色为红色或绿色,具体取决于我使用 getDBValue(); 从数据库中获取的值(这可行)。

问题是,当第一次打开活动时,列表视图被膨胀,所有列表视图项目都具有相同(不正确)的绿色背景颜色。当我开始滚动时,背景设置正确。

当列表视图膨胀时如何获得正确的背景颜色以及我的程序“错误”在哪里?

我已经对其进行了调试,dbValue 正在返回正确的值。

这是我的代码:

public View getView(int position, View convertView, ViewGroup parent) {
    return createViewFromResource(position, convertView, parent, mResource);
}

private View createViewFromResource(int position, View convertView,
        ViewGroup parent, int resource) {
    View v;

    if (convertView == null) {
        // first time views are created
        v = mInflater.inflate(resource, parent, false);
    } else {
        v = convertView;
    }

    String dbvalue = getDBValue();

    if(!dbvalue.equals("me")){
            v.setBackgroundColor(Color.argb(230, 255, 0x00, 0x00));
    }else{
            v.setBackgroundColor(Color.argb(230, 0x00, 255, 0x00));
    }

    setViewText((TextView) v, text);

    return v;
}

【问题讨论】:

  • 绿色是“其他”条件?如果是,可能你的 dbvalue 没有返回正确的值(在你第一次构建视图时)
  • 这是我的想法,但是调试时,值是正确的。

标签: android listview listadapter


【解决方案1】:

我在我的应用中做了这件事,

请为此设置可绘制,并在视图中应用, 这里我分享设置drawable的方法,检查一下。

请在createViewFromResource中调用这个方法,这样就可以了。

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private void setdrwable(Drawable drawable,View view)
{
    if(Build.VERSION.SDK_INT>=16)
    {
        view.setBackground(drawable);
    }
    else
    {
        view.setBackgroundDrawable(drawable);
    }
}

【讨论】:

    猜你喜欢
    • 2013-09-29
    • 2015-04-19
    • 2019-11-02
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    相关资源
    最近更新 更多