简体   繁体   中英

Android set single item background color in listview

I need to change color on selected item in list view, i know how to do that in click method, but the thing is that I want to set it then i load new activity. In that activity I'm creating listview and then I want to change one item background color from that list.

I have tried

this.slideMenuList = (ListView) findViewById(R.id.listSlideMenu);
    ArrayAdapter<String> adapter2 =
            new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.menuListResut);
    this.slideMenuList.setAdapter(adapter2);

    this.slideMenuList.getChildAt(0).setBackgroundColor(R.color.red);

but I get NullPointer

You need a custom adapter; you're probably getting a NPE because the views aren't rendered until they're needed, and you can't do that reliably as-is. Write your own adapter class and set the background color after the view has been inflated, like so:

public class MyAdapter extends BaseAdapter {
  @Override
  public View getView(int i, View convertView, ViewGroup viewGroup) {
    convertView = mInflater.inflate(your layout); // Pseudo-code!
    if (i == 0) {
      convertView.setBackgroundColor(R.color.red);
    }
  }
}

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