简体   繁体   中英

listview each item dynamically change background color

I have more specific case than just change background color.

I have 1 listview, in every listview item I have 2 textviews. All information I am showing in those listview items textviews is coming from server.

One parameter I am getting is color code (eg. #138F6A). Now, I need to take this color code (I am inserting as a value in textview) and change this listview item specific textview background color according to color code value I have from server.

How can I do that? How can I set colorView textview background as color I get from server for this listview item?

    public void OnCreateActivity() {    
    ...
    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
    XMLParser objektinimi_parser = new XMLParser(); 
    ...
     // looping through all item nodes <item>
            for (int i = 0; i < ndlist.getLength(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                Element myelem = (Element) ndlist.item(i);                      
    String bronID = objektinimi_parser.getValue(myelem, "BRON_ID");
    String color= objektinimi_parser.getValue(myelem, "COLOR");

    map.put(BRON_ID, bronID);
    map.put(COLOR, color);
    menuItems.add(map);
    }

    ListAdapter adapter = new SimpleAdapter (this, menuItems,
                    R.layout.kirjed,
                    new String[] { BRON_ID, COLOR }, 
                    new int[] { R.id.bronid, R.id.colorView });
    setListAdapter(adapter);
            ListView lv = getListView();

Thank you!

You can extend the adapter and set the background colour in the getView method:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    view.setBackgroundColor(theColour);
    return view;
}

This will work fine if you don't need press states etc.

If you do, you'd need to use a ColorStateList and setBackgroundResource instead, see: http://developer.android.com/reference/android/content/res/ColorStateList.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM