Change background of first item in ListView to red

时间:2016-02-12 21:38:50

标签: java android listview android-studio

I have a listView called listv and I'm populating the listView with an array. I want the background of the first item in my listView to be colored red. I can populate the list however I can't get the backgrounds first item in the list to turn red.

This is what I tried. My code is as fallows

My Class

_blank

xml

private ArrayList<String> arrayList;
private ArrayAdapter<String> adapter;
private EditText txtInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_deadlines);
    final ListView listView = (ListView)findViewById(R.id.listv);
    String[] items= {"HCI","ITM","Presentation"};
    arrayList=new ArrayList<>(Arrays.asList(items));
    adapter=new ArrayAdapter<String>(this,R.layout.list_item,R.id.txtitem,arrayList);
    listView.setAdapter(adapter);

    txtInput=(EditText)findViewById(R.id.txtinputs);


            if(R.id.listv == 0)
                listView.setBackgroundColor(Color.parseColor("#fffff"));


    });

}

2 个答案:

答案 0 :(得分:0)

You could use a custom ArrayAdapter, override getView() and in it check if "position" == 0 then change the background of the item to what you prefer. I beleive it is called for every item, after notifyDataSetChanged() has been invoked.

答案 1 :(得分:0)

This is not the correct approach. Rendering each row happens inside the adapter. You have to define your own adapter or you can extend from ArrayAdapter. In its getView() method, you call the base class getView first and if the position is zero, then you set the background color.

if(sessionStorage.getItem('year')){ // <-- Problem here. You've forgotten if statement bracket.
    $('#vehic_sel_year').val(sessionStorage.getItem('year'));
    $("#vehic_sel_trim").load("/v/vehicle-selection/cache/" + sessionStorage.getItem('year') + ".txt");
}

You could also add a header view to accomplish this.

Unless you are required to use ListView it maybe better to consider RecyclerView.