0

I have a listview, and I want to set the background color of the first item at onCreate. I tried this:

    mDrawerList = (ListView) findViewById(R.id.navList);
    DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
    mDrawerList.setAdapter(adapter);
    View view = mDrawerList.getChildAt(1);
    view.setBackgroundColor((parseColor("#008CC3")));

But it gives NPE. How can I do this?

Tamas Koos
  • 1,053
  • 3
  • 15
  • 35

1 Answers1

0

As you already have your own ListAdapter (DrawerListAdapter) class you should be able to override the getView(int position, View convertView, ViewGroup parent) method in it. In there you can simply do

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    if (position == 0) {
        view.setBackgroundColor(Color.parseColor("#008CC3"));
    }
    return view;
}

Additional tips:

  • You want to get the first item but are calling getChildAt(1), this will actually give you the second item.
  • ListViews are somehow deprecated, you should look into RecyclerViews
Syex
  • 1,320
  • 1
  • 12
  • 23
  • Could you show me the exact code that I should paste in there? – Tamas Koos Feb 14 '17 at 18:27
  • Updated the comment. Assuming it's extending `ListAdapter` or `ArrayAdapter` – Syex Feb 14 '17 at 18:31
  • Thank you. But later how can I change it back to transparent? Because I tried to do that on onItemClick, but it's not working. – Tamas Koos Feb 14 '17 at 18:37
  • mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView> parent, View view, int position, long id) { parent.getChildAt(position).setBackgroundColor((parseColor("#008CC3"))); parent.getChildAt(lastPosition).setBackgroundColor(0x00000000); selectItemFromDrawer(position); lastPosition = position; } }); – Tamas Koos Feb 14 '17 at 18:38
  • The lastPosition is set to 0 by default, so that on the first click the first item's background turns transparent. – Tamas Koos Feb 14 '17 at 18:39
  • I guess for that check other solutions like http://stackoverflow.com/questions/5853719/highlighting-the-selected-item-in-the-listview-in-android – Syex Feb 14 '17 at 18:44
  • I accept your answer, because it does what I wanted, even though it doesn't completely solve my problem. – Tamas Koos Feb 14 '17 at 18:48