Search code examples
androidlistviewlistadapter

Wrong backgroundcolor on ListView inflate


So I have a ListView that uses a custom adapter. I want the background color of an item be either red or green, depending on a value I get out of my database with getDBValue(); (this works).

The problem is, when the activity is first opened, and so the listview is inflated, all listview items have the same (not correct) green background color. When I start scrolling though, the background are set correctly.

How do I get the right background color when listview inflates and where does my program "error"?

I already have debugged it and the dbValue is returning the correct value.

This is my code:

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

Solution

  • I done this thing in my app,

    Please make drawable for that, and apply in view, here i share method which set drawable, check it.

    Please call this method in createViewFromResource So, this will work.

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